最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

functions - How to get current post type?

programmeradmin1浏览0评论

I want to get the current post type inside functions.php

This is a function to sort reviews by custom meta key. I've managed to get the reviews sorted using the following code:

// Sort reviews in category page by customers rating - START

function pre_get_posts_hook($wp_query) {

    if( is_admin() ) {
        return $wp_query;
    }

    if ( $wp_query->is_main_query() && ( is_category() || is_archive() ) )
    {
        $wp_query->set( 'orderby', 'meta_value' );
        $wp_query->set( 'meta_key', 'user_average' );
        $wp_query->set( 'order', 'DESC' );
        return $wp_query;
    }
}

add_filter('pre_get_posts', 'pre_get_posts_hook' );

// Sort reviews in category page by customers rating - END

But, when I add && $wp_query->is_post_type_archive('review') in order to check if the current post type is 'review' before sorting, the entire function does not seem to work!

// Sort reviews in category page by customers rating - START


function pre_get_posts_hook($wp_query) {

    if( is_admin() ) {
        return $wp_query;
    }

    if ( $wp_query->is_main_query() && ( is_category() || is_archive() ) && $wp_query->is_post_type_archive('review') )
    {
        $wp_query->set( 'orderby', 'meta_value' );
        $wp_query->set( 'meta_key', 'user_average' );
        $wp_query->set( 'order', 'DESC' );
        return $wp_query;
    }
}

add_filter('pre_get_posts', 'pre_get_posts_hook' );

// Sort reviews in category page by customers rating - END

Any idea on how to fix this problem?

Thanks in advance.

发布评论

评论列表(0)

  1. 暂无评论