How to Add masonary jquery plugin to WordPress theme –easiest method

viralNews WordPress theme

A lot of methods are already given to add jquery plugin inside your WordPress theme or plugin. The HTML and CSS methods listed in its developer website has a minimum size of 28KB but the masonry plugin bundled with WordPress is its striped version and its size is only 2KB in size.

So instead of using the jquery plugin from the developer site, I would recommend you to use masonry plugin comes with WordPress.

The proper way to add bundled jquery inside your theme is – Just add the following code inside your functions.php file

function theme_java_scripts(){
wp_enqueue_script( 'jquery-masonry');
add_action( 'wp_enqueue_scripts', 'theme_java_scripts' );

Now its time to activate masonry inside your theme. One method is to add the following code inside your footer.php file before your closing body tag like this


Now the code will look like this

jQuery( document ).ready( function( $ ) {
$( ‘#grid’ ).masonry();
} );

but we could not recommend you to hardcode this. Instead of that we would recommend you to add the following code inside functions.php file

if ( ! function_exists( 'slug_masonry_exists' )) :
function slug_masonry_exists() { ?>
jQuery( document ).ready( function( $ ) {
$( '#grid' ).masonry();
} );
<?php }
//add to wp_footer   - So make it very sure your theme has   <?php wp_footer();?> inside your footer.php file otherwise this function will not execute at all.
add_action( 'wp_footer', 'slug_masonry_exists' );
endif; // ! slug_masonry_init exists

Now its time to add an ID grid as you can see in the above code. The basic idea here is the ID must be placed in the class or ID that covers the whole row. Like we are using the same in a WordPress theme for ViralNews

<div class="row" id="grid">
<?php while(have_posts()) : the_post(); ?>
<div class="col-lg-3 col-md-3 col-sm-4 col-xs-12">
<div class="panel pandel-default">
<a href="<?php the_permalink();?>"><?php the_post_thumbnail(array(360,240), array('class'=>'img-responsive') );?></a>
<div class="panel-footer">
<h3 style="width:100%;overflow:hidden;height:1.1em;"><?php the_title();?></h3>
<p> Category:<?php the_category(', '); ?></p>
<?php the_excerpt();?>
<?php endwhile ;?>
</div>   <!--end of row-->

Now save your work and enjoy masonry style your blog posts.

Related Posts

Leave a Reply

Your email address will not be published.