[原创]wordpress中修改文章排序字段的几种方法

关于wordpress排序,默认依post_date排序;wordpress内定允许的排序字段包括:

'post_name', 'post_author', 'post_date', 'post_title', 'post_modified','post_parent', 'post_type', 'name', 'author', 'date', 'title', 'modified','parent', 'type', 'ID', 'menu_order', 'comment_count', 'rand'

如果需要修改文章依ID字段排序,方法大致有:
1、可以向posts_orderby这个hooks添加内容。位于wp-includes/query.php中 3206行。

如:

add_filter( 'posts_orderby', 'wpdit_custom_orderby' );
function wpdit_custom_orderby( $orderby ) {
    $orderby = "ID ASC";
    return $orderby;
}

上面的代码是改变了全局的排序方式。

2、如果仅想在需要的地方设定不同的排序,可参考下面的代码:

     $args = array(
        'orderby'   => 'ID', //直接设定条件
     );

在允许排序的字段当中,’rand’也是个有意思的应用,早些时间有分享随机获取文章的具体方法,可移步参考:
《wordpress随机文章》

另外,百度知道里道友提出这样的问题:

wordpress 评论数排序文章问题
 '', 
		'post_status' => 'publish', // 只选公开的文章. 
		'post__not_in' => array($post->ID),//排除当前文章 
		'caller_get_posts' => 1, // 排除置顶文章. 
		'orderby' => 'comment_count', // 依评论数排序. 
		'posts_per_page' => $post_num 
	); 
	$query_posts = new WP_Query(); 
	$query_posts->query($args); 
	while( $query_posts->have_posts() ) :	$query_posts->the_post(); 	?> 
		
  • 具体可查看知道里的详细信息以及我的回复:
    http://zhidao.baidu.com/question/241553452831217284
    具体代码为:

        global $wp_query;
        $args= array(
            'post_type'             => 'post',
            'post_status'           => 'publish', // 只选公开的文章. 
            'post__not_in'          => array(1), //排除当前文章
            'orderby'               => 'comment_count', // 依评论数排序. 
            'ignore_sticky_posts'   => true, // 排除置顶文章.
            'posts_per_page'        => 18
        );    
        $wp_query = new WP_Query( $args ); 
         
        var_dump($wp_query->query);
        var_dump($wp_query->request);
        if ( have_posts() ) : 
            while ( have_posts() ) : the_post();
                the_title();
                // to do loop
            endwhile;
        endif;
        wp_reset_query();
    

    One thought on “[原创]wordpress中修改文章排序字段的几种方法”

    发表评论

    您的电子邮箱地址不会被公开。 必填项已用*标注