您不应该使用query_posts
完全一切都在this post 我最近做过。查看我在那篇文章中给出的所有链接
分页不起作用的一个大问题是默认的二十一分页函数,twentytwelve_content_nav
, 不提供自定义查询。但是,您可以重写此函数,因为它被包装在if ( ! function_exists() )
条件语句。
首先,用于自定义查询。如前所述,不要也永远不要使用query_posts
, 大多数情况下,它在分页时完全失败。这是你要用的WP_Query
. 因此,请将您的页面模板更改为以下内容(这里只有一点,category_name
使用类别slug, 不name)
<?php
/*
Template Name: C Programming Category page
*/
get_header(); ?>
<div id="primary" class="site-content">
<div id="content" role="main">
<?php
$args = array(
\'category_name\' => \'c-programming\'
);
$my_query = new WP_Query($args); ?>
<?php if ( $my_query->have_posts() ) : ?>
<?php /* Start the Loop */ ?>
<?php while ( $my_query->have_posts() ) : $my_query->the_post(); ?>
<?php get_template_part( \'content\', \'custom\' ); ?>
<?php endwhile; ?>
<?php twentytwelve_content_nav( \'nav-below\' ); ?>
<?php else : ?>
<article id="post-0" class="post no-results not-found">
<?php if ( current_user_can( \'edit_posts\' ) ) :
// Show a different message to a logged-in user who can add posts.
?>
<header class="entry-header">
<h1 class="entry-title"><?php _e( \'No posts to display\', \'twentytwelve\' ); ?></h1>
</header>
<div class="entry-content">
<p><?php printf( __( \'Ready to publish your first post? <a href="%s">Get started here</a>.\', \'twentytwelve\' ), admin_url( \'post-new.php\' ) ); ?></p>
</div><!-- .entry-content -->
<?php else :
// Show the default message to everyone else.
?>
<header class="entry-header">
<h1 class="entry-title"><?php _e( \'Nothing Found\', \'twentytwelve\' ); ?></h1>
</header>
<div class="entry-content">
<p><?php _e( \'Apologies, but no results were found. Perhaps searching will help find a related post.\', \'twentytwelve\' ); ?></p>
<?php get_search_form(); ?>
</div><!-- .entry-content -->
<?php endif; // end current_user_can() check ?>
</article><!-- #post-0 -->
<?php endif; // end have_posts() check ?>
<?php wp_reset_postdata(); ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_sidebar( \'front\' ); ?>
<?php get_footer(); ?>
现在,收到
twentytwelve_content_nav
函数到您的子主题函数。php。您将对此进行修改。这是修改后的代码。完成它并检查更改,我已经对这些进行了评论
function twentytwelve_content_nav( $html_id ) {
global $wp_query, $my_query; // add your custom query variable
$html_id = esc_attr( $html_id );
if ( $wp_query->max_num_pages > 1 || $my_query->max_num_pages > 1 ) : ?> // Add your custom query to the max_num_parameter
<nav id="<?php echo $html_id; ?>" class="navigation" role="navigation">
<h3 class="assistive-text"><?php _e( \'Post navigation\', \'twentytwelve\' ); ?></h3>
<div class="nav-previous"><?php next_posts_link( __( \'<span class="meta-nav">←</span> Older posts\', \'twentytwelve\' ) ); ?></div>
<div class="nav-next"><?php previous_posts_link( __( \'Newer posts <span class="meta-nav">→</span>\', \'twentytwelve\' ) ); ?></div>
</nav><!-- #<?php echo $html_id; ?> .navigation -->
<?php endif;
}
这应该可以