Support » Plugins » Hacks » Enqueue script from a Customizer setting

  • In relation to using the masonry script in WordPress, I have it enqueued normally, but I’d like to load the script “only” when a theme setting is set from the Customizer. For example, my theme has several blog layout/styles, one is the masonry, so if I have the masonry option chosen, I want the script to show, otherwise not.

    I’m seeing an error on pages when it’s loaded but not needed as “Element Null”.

    Basically I need to keep the enqueue of this masonry in the functions.php, but have it so it loads only when my theme option is chosen.

    Right now I have this:

    if ( is_home() || is_archive() ) {
    		wp_enqueue_script( 'masonry' );
    		wp_enqueue_script( 'masonry-helper', get_template_directory_uri().'/js/masonry-helper.js', array('jquery'), '', true );
    	}
Viewing 3 replies - 1 through 3 (of 3 total)
  • Ah…nevermind, apparently it works just like any other theme template. I did it like this:

    $blogstyle = get_theme_mod( 'blog_style', '' );
    switch ($blogstyle) {
    	case "masonry" :
    	if ( is_home() || is_archive() ) {
    		wp_enqueue_script( 'masonry' );
    		wp_enqueue_script( 'emphasize-pro-masonry-helper', get_template_directory_uri().'/js/masonry-helper.js', array('jquery'), '', true );
    	}
       break;
    }

    I stand corrected….turns out the scripts are loading on the blog home and archives when I choose a different blog style from the WP Customizer, other than the “Masonry” option.

    Is there an alternative to make this work?

    My theme offers several blog layouts and styles, with the Masonry being one.

    OK….after exploding a few brain cells, I believe I found the solution:

    $blogstyle = get_theme_mod( 'blog_style', '' );
    if ( $blogstyle == 'masonry' || $blogstyle == 'masonrywide') {
    	if ( is_home() || is_archive() ) {
    		wp_enqueue_script( 'masonry' );
    		wp_enqueue_script( 'emphasize-pro-masonry-helper', get_template_directory_uri().'/js/masonry-helper.js', array('jquery'), '', true );
    	}
    }
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Enqueue script from a Customizer setting’ is closed to new replies.