Conditionally load external JS per post basis?

Community Forums Forums Design Tips and Tricks Conditionally load external JS per post basis?

This topic is: resolved

This topic contains 2 replies, has 2 voices, and was last updated by  lvvvvvl 6 months, 1 week ago.

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #67267

    lvvvvvl
    Participant
    Post count: 14

    Hello,

    I’m trying to load this http://www.addthis.com/labs/photo-sharing#.UmC11FBmh8E script per single post basis rather than activate the addthis plugin throughout the whole site.

    I know this must be possible with wp_enqueue_script() somehow and an IF IS_Single conditional statement but the tutorials I’ve found online only deal with plugins that are already registered, and how to deregister them and then load the .js file inside the plugin folder. There’s none in particular about external javascripts (like http://s7.addthis.com/js/300/addthis_widget.js#pubid=YOUR PROFILE ID HERE]) .

    Any advice will be much appreciated!

    #67273

    Gary Jones
    Moderator
    Post count: 635

    The source of the script is irrespective – if you want to load a script from a local plugin, or from an external URL, the only thing that changes in the wp_enqueue_script() call is the second argument – the URI path to the script. Try tweaking and adding the following to your child theme functions.php file.

    add_action( 'wp_enqueue_scripts', 'prefix_enqueue_single_scripts' );
    /**
     * Enqueue scripts for this theme that should only be loaded on single entries.
     *
     * @author Gary Jones
     * @link   <a href="http://www.studiopress.com/forums/topic/conditionally-load-external-js-per-post-basis/" rel="nofollow">http://www.studiopress.com/forums/topic/conditionally-load-external-js-per-post-basis/</a>
     *
     * @return null Return early if not a single entry.
     */
    function prefix_enqueue_single_scripts() {
    	if ( ! is_single() )
    		return;
    	wp_enqueue_script( 'prefix-add-this', 'http://s7.addthis.com/js/300/addthis_widget.js#pubid=YOURPROFILEID', array(), '1.0.0', true );
    }
    

    Changes in Genesis 2.0 – the ultimate guide to every single change in Genesis Framework 2.0, 2.0.1 and 2.0.2 (all 159 of them!) | @GaryJ

    #67278

    lvvvvvl
    Participant
    Post count: 14

    Awesome! thank you!

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Conditionally load external JS per post basis?’ is closed to new replies.