Web Development & WordPress

Learning Plugins Development: Part 3

Here i am trying to create a custom WordPress plugin that generates a shortcode [post_title_with_pagination] to display post titles with pagination. This step-by-step guide will help you set up the plugin and use it in your WordPress site effectively. Please check Learning Plugins Development: Part 1 to find out the steps.

<?php
/*
Plugin Name: Test Plugin
Plugin URI: https://facebook.com
Author: Maya Nova
Author URI: https://google.com
Description: This is a test plugin

*/
 
function post_title_with_pagination_function() {
    ob_start(); // Start output buffer
    global $paged;
    if (!isset($paged) || !$paged){
        $paged = 1;
    }
    $paged = ( get_query_var('paged') ) ? absint( get_query_var('paged') ) : 1;
    if (get_query_var('paged')) {
        $paged = get_query_var('paged');
    } elseif (get_query_var('page')) { // Support for paginated posts
        $paged = get_query_var('page');
    } else {
        $paged = 1;
    }
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => 3, 
        'orderby' => 'post_title',
        'order' => 'ASC',
        'paged' => $paged,
    );
    $the_query = new WP_Query($args);

    if ($the_query->have_posts()) {
       $output= "<ul>";
        while ($the_query->have_posts()) {
            $the_query->the_post();
            $output .= "<li>" . get_the_title() . "</li>";
        }
        $output .= "</ul>";

        $big = 999999999; // need an unlikely integer

        $output.= paginate_links(array(
            'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
            'format' => '?paged=%#%',
            'current' => max(1, get_query_var('paged')),
            'total' => $the_query->max_num_pages,
        ));
    }
return $output;
  
      ob_get_clean(); // Return buffered content
}

add_shortcode("post_title_with_pagination", "post_title_with_pagination_function");
 

Leave a comment