functions - How to get current post type?

admin2025-04-22  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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745289684a294607.html

最新回复(0)