我有几种自定义的帖子类型(通过CPT UI插件创建)。我想在我的页面上显示这些帖子类型的帖子,例如“新闻”。我创建了一个页面并在其中插入了短代码[show_posts post_type="novyny"].
我有一个插件可以处理这个短代码
function foo($args){
$post_type = $args[\'post_type\'];
$custom_post_type = new WP_Query(
array(
\'post_type\' => $post_type,
\'orderby\' => \'date\',
\'order\' => \'DESC\',
\'posts_per_page\' => 4
)
);
if( $custom_post_type->have_posts() ) :
while( $custom_post_type->have_posts() ): $custom_post_type->the_post(); ?>
<h1><a href="<?php the_permalink(); ?>"><?php the_title() ?></a></h1>
<p> <?php the_modified_date(); echo ", "; the_modified_time() ?></p>
<p> <?php the_excerpt() ?></p>
<?php endwhile;
the_posts_pagination();
endif;
wp_reset_postdata();
}
add_shortcode(\'show_posts\', \'foo\');
将显示帖子,但页面上不会显示分页博客,即使要显示的帖子超过4篇。怎么了?
最合适的回答,由SO网友:Sumit 整理而成
the_posts_pagination
使用global
查询和全局查询没有分页。因此,这是WordPress的正确行为。
要解决此问题,请将自定义查询分配给全局查询,然后在循环后再次恢复全局查询。
function foo($args){
$post_type = $args[\'post_type\'];
global $wp_query;
$original_query = $wp_query;
$custom_post_type = new WP_Query(
array(
\'post_type\' => $post_type,
\'orderby\' => \'date\',
\'order\' => \'DESC\',
\'posts_per_page\' => 4
)
);
$wp_query = $custom_post_type;
if( $custom_post_type->have_posts() ) :
while( $custom_post_type->have_posts() ): $custom_post_type->the_post(); ?>
<h1><a href="<?php the_permalink(); ?>"><?php the_title() ?></a></h1>
<p> <?php the_modified_date(); echo ", "; the_modified_time() ?></p>
<p> <?php the_excerpt() ?></p>
<?php endwhile;
the_posts_pagination();
endif;
wp_reset_postdata();
$wp_query = $original_query;
}
SO网友:Vlad
谢谢大家,伙计们。我是这样解决的:
添加了$paged
变量:$paged = ( get_query_var(\'page\') ) ? get_query_var(\'page\') : 1;
(用于main page 您应该使用get_query_var(\'page\')
, 对于other pages - $paged = ( get_query_var(\'paged\') ) ? get_query_var(\'paged\') : 1;
)并为WP\\u查询添加了一个新参数:\'paged\' => $paged
我的代码现在:
function foo($args){
$post_type = $args[\'post_type\'];
/* Added $paged variable */
$paged = ( get_query_var(\'paged\') ) ? get_query_var(\'paged\') : 1;
global $wp_query;
$original_query = $wp_query;
$query_args = array(
\'post_type\' => $post_type,
\'posts_per_page\' => 3,
/* And added a new argument for WP_Query */
\'paged\' => $paged
);
$custom_post_type = new WP_Query( $query_args );
$wp_query = $custom_post_type;
if ( $custom_post_type->have_posts() ) :
while ( $custom_post_type->have_posts() ) :
$custom_post_type->the_post(); ?>
<h1><a href="<?php the_permalink(); ?>"><?php the_title() ?></a></h1>
<p> <?php the_modified_date(); echo ", "; the_modified_time() ?></p>
<p> <?php the_excerpt() ?></p>
<?php endwhile;
the_posts_pagination();
endif;
wp_reset_postdata();
$wp_query = $original_query;
}