1

I'm developing a site that uses a Artist custom post type and I need to query all posts of this type in a page template. I need to set the is_post_type_archive property to true too to filter this query using the posts_orderby filter. I'm using the following code, but it seems WordPress is ignoring the third line:

$args = array('post_type' => 'artist');
$wp_query = new WP_Query( array_merge( $args, array('nopaging' => true) ) );
$wp_query->is_post_type_archive = true;

This is the filter:

function artist_posts_orderby( $orderby )
{
    if (is_post_type_archive('artist')) {
        $orderby = "RIGHT(post_title, LOCATE(' ', REVERSE(post_title)) - 1) ASC";
    }
    return $orderby;
}
add_filter('posts_orderby', 'artist_posts_orderby' );

Any ideas?

Thanks in advance

1

I rewrote the code and now it works

The loop:

$args = array('post_type' => 'artist');
$wp_query = new WP_Query( array_merge( $args, array('nopaging' => true) ) );

The filter:

function theme_posts_orderby( $orderby, $query )
{
    if ($query->query_vars['post_type'] == 'artist') {
        // order artists by last name
        $orderby = "RIGHT(post_title, LOCATE(' ', REVERSE(post_title)) - 1) ASC";
    }
    return $orderby;
}
add_filter('posts_orderby', 'theme_posts_orderby', 10, 2 );
0

WP_Query retrieves posts right when it's created (in constructor). By the time you are modifying property it is already processed and results are stored.

You probably shouldn't be reusing main $wp_query object and global methods for this either.

Your question doesn't give enough details to suggest how to target query more precisely for your requirements, however there is always simple approach - add your filter right before query and remove right after.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.