WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Getting is_single to work in functions.php (3 posts)

  1. ggg377
    Member
    Posted 1 year ago #

    Hi, I've encountered what seems to be a syntax error on my behalf. I would like to use this code in my functions.php:

    if ( is_single() ) {
    add_action('init','copy_script');
    
    function copy_script() {
        wp_enqueue_script( 'copy-script-js', get_template_directory_uri() . '/js/copy.js', false, null );
    }
    }

    However, the javascript doesn't get loaded up anywhere. If I use it like this, it gets loaded properly, but for all pages:

    add_action('init','copy_script');
    
    function copy_script() {
        wp_enqueue_script( 'copy-script-js', get_template_directory_uri() . '/js/copy.js', false, null );
    }

    I'm thinking this is a syntax issue. I want the script to be loaded up only on single pages. I would be glad if anyone could help me with this.

    ggg377

  2. keesiemeijer
    moderator
    Posted 1 year ago #

    Try to enqueue on the "wp_enqueue_scripts" action hook:

    add_action('wp_enqueue_scripts','copy_script');
    
    function copy_script() {
       if ( is_single() ) {
        wp_enqueue_script( 'copy-script-js', get_template_directory_uri() . '/js/copy.js', false, null );
       }
    }

    http://codex.wordpress.org/Function_Reference/wp_enqueue_script

  3. ggg377
    Member
    Posted 1 year ago #

    Thanks keesiemeijer, that helped :)

Topic Closed

This topic has been closed to new replies.

About this Topic