Forums

How to add javascript with special shortcode only (4 posts)

  1. Ander
    Member
    Posted 2 weeks ago #

    I need to add javascript in header only if page contains shordcode in order to optimize web size.

    Example code of plugin:

    wp_register_script('script-main', WP_PLUGIN_URL . '/main/js/table.js'
    add_shortcode( 'gal-main' , 'main_page' );

    function main_js(){
    wp_enqueue_script('script-main');
    }
    function main_page() {
    add_action('init','main_js');
    #....shortcode...
    }

    It does not work.

  2. apljdi
    Member
    Posted 2 weeks ago #

    1) Your first line is broken. Either you've forgotten a closing parenthesis and semicolon or you are trying to pass the function the wrong kind of thing. The wp_register_script isn't going to accept an 'add_shortcode' function call. Taken straight from wp-includes/functions.wp-scripts.php your options are: wp_register_script( $handle, $src, $deps = array(), $ver = false, $in_footer = false ). And either way the line triggers a T_STRING error.

    2) Why are you adding your action to 'init' instead of, say, 'wp_print_scripts'?

    You've got an interesting problem. In order to know that you have shortcodes I'm thinking you need to be able to read your queried post array, which means you need to run a function inside the Loop to decide whether to insert the script. That is too late to print anything to the header but you should be able to print to the footer.

  3. Ander
    Member
    Posted 2 weeks ago #

    1) Yes, it was copy-paste error )

    2) According to "init" - I tried to find out an another hook.

    Yes, I thinked that they are precessed in the different contexts, so I can not add a javascript to header already.

    it would be the great if "is_shortcode" presents for headers :)

    Is there any way to use javascript on specific template only using is_page_template() like is_admin ?

  4. apljdi
    Member
    Posted 2 weeks ago #

    Is there any way to use javascript on specific template only using is_page_template() like is_admin ?

    Sure. Use is_page_template('templatename.php'). Its in the codex. Seems like that should work.

Reply

You must log in to post.

About this Topic