2

I'm developing a plugin which has its own table. I need to display the data from the table in the Wordpress frontend (for example: category page). I don't need to JOIN this table with posts table, I just need to display the data from the table, with pagination. I need a separate page/custom template from my plugin directory (talking in a context of MVC frameworks — controller), on which this data should be displayed and paginated.

Please give me an advice, what is the best practice to implement it?

Thanks.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
Dima Knivets
  • 2,418
  • 7
  • 28
  • 40

1 Answers1

3

If I understood your question then I think you need to add template_include hook to use Custom template/page from your plugin directory and you can do it like

add_filter('template_include', 'my_template', 1, 1); 
function my_template($template) { 
    global $post; 
    if($post->post_content == '[myPluginPage]') 
        return dirname(__FILE__) . '/my_pligin_template.php'; 
        return $template; 
}

You should paste the code given above in your plugin file and also create a file in your plugin folder with name my_pligin_template.php or whatever you want but in this case in the first return statement you have to change the file name too.

Now you have to create a page in wordpress admin to show the page in the menu bar and just paste [myPluginPage] as the content. Notice if($post->post_content == '[myPluginPage]'), this will check whether it's your plugin page or not whenever you click on any menu item and if it finds the word [myPluginPage] in the content then it will return the custom template and you will be at that page.

Now you need to fetch your data from database and to do it you should write the code in this custom template file (my_pligin_template.php). To do it you can write

global $wpdb;
$pagenum = isset( $_GET['pagenum'] ) ? absint( $_GET['pagenum'] ) : 1;
$limit = 10;
$offset = ($pagenum-1) * $limit;
$total = $wpdb->get_var( "SELECT COUNT(*) FROM yourtable" );
$num_of_pages = ceil( $total / $limit );

$qry="select * from yourtable LIMIT $offset, $limit";
$result=$wpdb->get_results($qry);
if($result):
    foreach($result as $row)
    {
        // code here
    }

    //Link for Pagination
    $page_links = paginate_links( array(
        'base' => add_query_arg( 'pagenum', '%#%' ),
        'format' => '',
        'prev_text' => __( '«', 'aag' ),
        'next_text' => __( '»', 'aag' ),
        'total' => $num_of_pages,
        'current' => $pagenum
    ) );
    if ( $page_links ) {
        echo '<div class="tablenav"><div class="tablenav-pages" style="margin: 1em 0">' . $page_links . '</div></div>';
    }
endif;
The Alpha
  • 143,660
  • 29
  • 287
  • 307