2016-05-31 83 views
0

我一直在谷歌搜索,看看与这一个有关的许多其他问题,但问题仍然存在。WordPress的WP_Query与分页

我试图得到分页查询,只显示页面1。如果您将页面的变量更改为任何其他数字,它将返回一个空数组。

这里是我使用的代码,也就是比别人我在其他问题看得非常相似:

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; 
$temp = $wp_query; 
$wp_query= null; 
$args = array(
       'posts_per_page' => 20, 
       'post_type'  => 'post', 
       'paged'   => $paged, 
       'category_name' => 'blog' 
); 
$wp_query = new WP_Query($args); 
$data = array(); 
while ($wp_query->have_posts()) : $wp_query->the_post(); 
    $obj = new stdClass; 
    $obj->id    = $post->ID; 
    $obj->title   = $post->post_title; 
    $obj->excerpt   = substr(str_replace(array("\r","\t","\n"), array('','',''), trim(strip_tags($post->post_content))), 0, 200).'...'; 
    $obj->slug   = str_replace('http://localhost/', '', get_permalink($post->ID)); 
    $obj->author_name  = get_user_by('id', $post->post_author)->user_login; 
    $obj->featured_image = wp_get_attachment_url(get_post_thumbnail_id($post->ID, 'post-thumbnails')); 
    array_push($data, $obj); 
endwhile; 

有什么不对?我猜不到它!

+0

也许尝试'page',而不是''paged' – Pierre

+0

@PierreLebedel你意思是'page'=> $ paged? – Apalabrados

+0

是的,因为[在文档](https://codex.wordpress.org/Class_Reference/WP_Query#Pagination_Parameters)都存在 – Pierre

回答

0

写在你的functions.php

//Pagination 
function custom_pagination($numpages = '', $pagerange = '', $paged='') { 

if (empty($pagerange)) { 
    $pagerange = 2; 
} 

/** 
* This first part of our function is a fallback 
* for custom pagination inside a regular loop that 
* uses the global $paged and global $wp_query variables. 
* 
* It's good because we can now override default pagination 
* in our theme, and use this function in default queries 
* and custom queries. 
*/ 
global $paged; 
if (empty($paged)) { 
    $paged = 1; 
} 
if ($numpages == '') { 
    global $wp_query; 
    $numpages = $wp_query->max_num_pages; 
    if(!$numpages) { 
     $numpages = 1; 
    } 
} 

/** 
* We construct the pagination arguments to enter into our paginate_links 
* function. 
*/ 
$pagination_args = array(
    'base'   => get_pagenum_link(1) . '%_%', 
    'format'   => 'page/%#%', 
    'total'   => $numpages, 
    'current'   => $paged, 
    'show_all'  => False, 
    'end_size'  => 1, 
    'mid_size'  => $pagerange, 
    'prev_next'  => True, 
    'prev_text'  => __('«'), 
    'next_text'  => __('»'), 
    'type'   => 'plain', 
    'add_args'  => false, 
    'add_fragment' => '' 
); 

$paginate_links = paginate_links($pagination_args); 

if ($paginate_links) { 
    echo "<nav class='custom-pagination'>"; 
    echo "<span class='page-numbers page-num'>Page " . $paged . " of " . $numpages . "</span> "; 
    echo $paginate_links; 
    echo "</nav>"; 
} 
} 

,并使用下面的代码哪里ü希望显示分页

<?php 
     if (function_exists(custom_pagination)) { 
      custom_pagination($cat->max_num_pages,"",$paged); 
     } 
     ?>