Masonry Posts In WordPress

Used before category names. Blog WordPress WordPress Development

WordPress add some features about Masonry list. To create Masonry list in WordPress, follow the steps.

Step 1 – Add JavaScript Files in Functions.php

Open functions.php file of the theme and add following codes in it.


function hs_enqueue_scripts(){
    wp_enqueue_script('jquery-masonry');
    wp_enqueue_script('hs-masonry-init', esc_url(get_stylesheet_directory_uri() . '/assets/js/masonry-init.js'), array('jquery-masonry'), '1', true);
}
add_action('wp_enqueue_scripts', 'hs_enqueue_scripts');

Step 2 – Create Initialize File

Go to “assets->js” folder of your theme and create “masonry-init.js” file. open the file and write below codes in it.

jQuery(document).ready(function ($) {
  $(".hs-masonry").masonry(); //targets the posts container
});

Step 3 – Add hs-masonry Class To Your List

Open your theme file where you display posts. Add the hs-masonry class before the list.

<div class="posts hs-masonry">
    <?php if (have_posts()) : ?>
        <?php while (have_posts()) :
            the_post(); 
            /*** other codes ... ***/
        endwhile; ?>
    <?php endif; ?>
</div>
Tags: