简体   繁体   English

将自定义帖子类型存档页面显示为主页

[英]Display custom post type archive page as homepage

The code I have is in my functions.php file and is displaying the custom post type 'events' posts as needed, but not sorting by the meta value 'upcoming_date'. 我拥有的代码在我的functions.php文件中,并根据需要显示自定义帖子类型“事件”帖子,但未按元值“ upcoming_date”进行排序。 It is not sorting in ascending order either. 它也不以升序排序。 Moreover, is it possible to sort by 2 metavalues? 此外,是否可以按2个元值排序? Please help. 请帮忙。

add_action("pre_get_posts", "cpt_front_page");
function cpt_front_page( $wp_query ){

    //Ensure this filter isn't applied to the admin area
    if(is_admin()) {
        return;
    }

    if($wp_query->get('page_id') == get_option('page_on_front')):

        $wp_query->set( 'post_type', 'events' );
        $wp_query->set( 'page_id', '' ); //Empty

        //Set properties that describe the page to reflect that
        //we aren't really displaying a static page     
        $wp_query->is_page = 0;
        $wp_query->is_singular = 0;
        $wp_query->is_post_type_archive = 1;
        $wp_query->is_archive = 1;

        //sort the posts by meta value in ascending order       
        $wp_query->meta_key = 'upcoming_date'; // <= IS THIS RIGHT?
        $wp_query->orderby = 'meta_value'; // <= IS THIS RIGHT?
        $wp_query->order = 'ASC'; // <= IS THIS RIGHT?

    endif;

}

This is most likely an issue with how you're storing your upcoming date and attempting to sort with it. 这很可能与您如何存储即将到来的日期并尝试对其进行排序有关。 You'll probably get the best chance of success by storing your dates in yymmdd format, and setting orderby to 'meta_value_num' , so that it sorts in a numerical order rather than a textual order. 通过以yymmdd格式存储日期,并将orderby设置为'meta_value_num' ,您可能会获得最大的成功机会,从而使它以数字顺序而不是文本顺序排序。

$wp_query->meta_key = 'upcoming_date';
$wp_query->orderby = 'meta_value_num';
$wp_query->order = 'ASC';

The documentation on orderby is a good reference. 关于orderby文档是一个很好的参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM