List custom data in Wordpress

烈酒焚心 提交于 2019-12-07 20:45:08

问题


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.


回答1:


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;


来源:https://stackoverflow.com/questions/12868475/list-custom-data-in-wordpress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!