Shortcode for show all post from any post type

In this post we will learn how to show your all post or page or any custom post type - show on a page by short code in short code many options like - [ show_post post_type='post' category='' tag='' post_pp='4' button_text='View Post' load_more='true' ]

This code copy and past it in functions.php file.

or create a new file and put this code in this file and include in functions.php file.

//custom code here 
function custom_enqueue_styles() {
	 wp_enqueue_script('jquery');
    wp_enqueue_style('bootstrap-css', 'https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css');
	 wp_enqueue_script('custom-load-more', get_template_directory_uri() . 'load-more.js', array('jquery'), null, true);
	    wp_localize_script('custom-load-more', 'ajax_params', array(
        'ajax_url' => admin_url('admin-ajax.php')
    ));

}
add_action('wp_enqueue_scripts', 'custom_enqueue_styles');

function custom_show_post_shortcode($atts) {
    // Define default attributes
    $atts = shortcode_atts(
        array(
            'post_type'   => 'post',
            'category'    => '',
            'tag'         => '',
            'post_pp'     => '4',  // Default posts per page
            'button_text' => 'Read more',
			'load_more'=>true
        ),
        $atts,
        'show_post'
    );
    $show_loadmore = $atts['load_more'];
    // Arguments for WP_Query
    $args = array(
        'post_type'      => $atts['post_type'],
        'posts_per_page' => $atts['post_pp'],
        'category_name'  => $atts['category'],
        'tag'            => $atts['tag'],
        'post_status'    => 'publish',
		'paged'          => 1
    );

    // Custom WP_Query
    $query = new WP_Query($args);

    // Start output buffering
    ob_start();

    if ($query->have_posts()) {
        echo '<div class="row" id="post-grid">';// Start Bootstrap row

        while ($query->have_posts()) : $query->the_post();
            ?>
            <div class="col-md-6 col-lg-3 mb-4">
                <div class="card" style='min-height: 100%;'>
                    <?php if (has_post_thumbnail()) : ?>
                        <img src="<?php the_post_thumbnail_url('medium'); ?>" class="card-img-top" alt="<?php the_title(); ?>">
                    <?php else:
					echo "<img src='https://developers.elementor.com/docs/assets/img/elementor-placeholder-image.png' class='card-img-top' alt=''/>";
					endif; ?>					
                    <div class="card-body">
                        <h5 class="card-title"><?php the_title(); ?></h5>
                        <div class="card-meta">
                            <small class="text-muted"><?php the_time('F j, Y'); ?> | <?php the_author(); ?></small>
                        </div>
                        <p class="card-text"><?php echo wp_trim_words(get_the_excerpt(),15); ?></p>
                        <a href="<?php the_permalink(); ?>" class="btn btn-primary"><?php echo esc_html($atts['button_text']); ?></a>
                    </div>
                </div>
            </div>
            <?php
        endwhile;		
        echo '</div>'; // End Bootstrap row
		if ($query->max_num_pages > 1 && $show_loadmore) {
            echo '<div class="text-center"><button id="load-more" class="btn btn-secondary" data-page="1" data-max="' . $query->max_num_pages . '" data-atts=\'' . json_encode($atts) . '\'>Load More</button> </div>';
        }

        wp_reset_postdata();
    } else {
        echo '<p>No posts found.</p>';
    }

    // Return the output
    return ob_get_clean();
}

// Register the shortcode
add_shortcode('show_post', 'custom_show_post_shortcode');

function custom_load_more_posts() {
    // Get current page
    $paged = isset($_POST['page']) ? $_POST['page'] : 1;
	
	$atts = isset($_POST['atts']) ?$_POST['atts']: array();
	 $args = array(
			'post_type'      => $atts['post_type'],
			'posts_per_page' => $atts['post_pp'],
			'category_name'  => $atts['category'],
			'tag'            => $atts['tag'],
			'post_status'    => 'publish',
			'paged'          => $paged
		);
    // Decode shortcode attributes from data-atts
    $query = new WP_Query($args);

    if ($query->have_posts()) {
        while ($query->have_posts()) : $query->the_post();
        
	 ?>
            <div class="col-md-6 col-lg-3 mb-4 post-item">
                <div class="card">
                    <?php if (has_post_thumbnail()) : ?>
                        <img src="<?php the_post_thumbnail_url('medium'); ?>" class="card-img-top" alt="<?php the_title(); ?>">
                    <?php endif; ?>
                    <div class="card-body">
                        <h5 class="card-title"><?php the_title(); ?></h5>
                        <p class="card-meta">
                            <small class="text-muted"><?php the_time('F j, Y'); ?> | <?php the_author(); ?></small>
                        </p>
                        <p class="card-text"><?php echo wp_trim_words(get_the_excerpt(), 20); ?></p>
                        <a href="<?php the_permalink(); ?>" class="btn btn-primary"><?php echo esc_html($atts['button_text']); ?></a>
                    </div>
                </div>
            </div>
            <?php
        endwhile;
    }

    wp_reset_postdata();
	
      die(); // Stop execution
}
add_action('wp_ajax_load_more', 'custom_load_more_posts');
add_action('wp_ajax_nopriv_load_more', 'custom_load_more_posts');

JavaScript and shortcode

You can put your shortcode and javascript in template or on html widget.

like this --
[show_post post_type='post' category='' tag='' post_pp='4' button_text='View Post' load_more='true']
< script>
jQuery(document).ready(function($) {
    $('#load-more').on('click', function() {
        var button = $(this);
        var page = button.data('page');
        var maxPages = button.data('max');
        var atts = button.data('atts');
        
        page++;

        // Make AJAX request
        $.ajax({
            url: ajax_params.ajax_url,
            type: 'POST',
            data: {
                action: 'load_more',
                page: page,
                atts: atts
            },
            beforeSend: function() {
                button.text('Loading...'); // Change button text
            },
            success: function(response) {
                $('#post-grid').append(response); // Append new posts
                button.data('page', page);

                // Check if we've reached max number of pages
                if (page >= maxPages) {
                    button.remove(); // Remove button if no more pages
                } else {
                    button.text('Load More');
                }
            }
        });
    });
});
</script>

Output somthing like this -

Post a Comment

0 Comments