如何自定义WordPress文章显示数量

一般WordPress显示文章数是可以通过在后台阅读设置中指定,后台设置会同步统一应用到首页、列表页、搜索页、标签页和分类页等等。然而我们会遇到根据页面类型指定每页显示文章数,那么如何自定义WordPress文章显示数量?这时候就需要需要我们手动写代码实现了,下面简单介绍下。

1、将下面代码添加到当前主题函数模板functions.php中,最终效果是搜索结果页面显示3篇文章,文章归档页面显示5篇。

add_action( ‘pre_get_posts’, ‘zm_set_posts_per_page’ );

function zm_set_posts_per_page( $query ) {

if ( ( ! is_admin() ) && ( $query === $GLOBALS[‘wp_query’] ) && ( $query->is_search() ) ) {

$query->set( ‘posts_per_page’, 3 );

}

elseif ( ( ! is_admin() ) && ( $query === $GLOBALS[‘wp_the_query’] ) && ( $query->is_archive() ) ) {

$query->set( ‘posts_per_page’, 5 );

}

return $query;

}

2、若想实现不同分类显示不同的文章数,修改其中的分类ID,实现指定的分类显示不同的文章数。

add_action( ‘pre_get_posts’, ‘zm_set_posts_per_page’ );

function zm_set_posts_per_page( $query ) {

if ( ( ! is_admin() ) && ( $query === $GLOBALS[‘wp_the_query’] ) && ( is_category(array(1,2)) ) ) {

$query->set( ‘posts_per_page’, 3 );

}

elseif ( ( ! is_admin() ) && ( $query === $GLOBALS[‘wp_the_query’] ) && ( is_category(array(3,4)) ) ) {

$query->set( ‘posts_per_page’, 5 );

}

elseif ( ( ! is_admin() ) && ( $query === $GLOBALS[‘wp_the_query’] ) && ( is_category(array(5,6)) ) ) {

$query->set( ‘posts_per_page’, 2 );

}

相关推荐: SSL证书中的RSA和ECC两种算法各有什么特点

RSA和ECC是SSL证书两种比较常用的算法,不同品牌的SSL证书所使用的算法会不太一样。本文简单介绍一下这两种算法的特点。 一、RSA(Rivest Shamir Adleman) 1、历史悠久。RSA是国际标准算法,在七十年代首次被描述,它被很好地理解并用…