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.

  • Your code appears to be fine on my end with and without $wp_query->is_post_type_archive('review'). Check to see if there are any other hooks or plugins that may be interfering. – Louis S Jul 28 at 21:59
  • @LouisS I know It is working, but i want to fire this function in review categories only. – Ahmed Elgameel Jul 29 at 4:06
  • This only fires on the 'review' custom post type archive page. Isn't that what you want? – Louis S Jul 29 at 9:06
  • Yes, that is what I want but it is not what it does. When I add the condition, it does not work! – Ahmed Elgameel Jul 29 at 23:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.