Sorting Posts by custom field

I’m trying to sort my posts by the custom field artwork_title. When I use the following code, I just end up with one particular category of posts no matter what category archive I’m on.

Also pagination shows the correct number of pages but going to the next page always shows the same set of posts. Anyone see what I’m doing wrong?

<?php $query = new WP_Query(
    array(
        'posts_per_page' => 20,
        'orderby' => 'meta_value',
        'meta_key' => 'artwork_title',
        'order' => 'ASC'
    ) ); ?>

            <?php while ( $query->have_posts() ) : $query->the_post(); ?>

                <?php get_template_part( 'content', get_post_format() );
                ?>

            <?php endwhile; ?>

@PieterGoosen suggested using pre_get_posts. I don’t have any experience with that but I threw this together but I’m not getting any results back using it. I’m sure it’s something stupid.

<?php add_action( 'pre_get_posts', 'sort_artwork_title' );?>

function sort_artwork_title( $query )
{
    if (is_admin()){
        return;
    }

   if( $query->is_main_query() && is_post_type_archive() ) {


            $query->set('orderby', 'artwork_title');
            $query->set('posts_per_page', '20');
            $query->set('order', 'ASC' );
        }
    return $query;
}

1 Answer
1

To expand on @pieter-goosen’s comment, you do indeed want to use pre_get_posts. In your example, by using WP_Query, you’re overwriting the entire query and just resetting most parts of it to default. In fact, you’re probably not seeing a specific category of posts at all. You should be seeing all posts since that’s the default of the WP_Query class.

So instead, use pre_get_posts which modifies an existing query rather than creating a brand new one. Here’s a [untested] snippet that should work in your functions.php file:

add_action( 'pre_get_posts', 'wpse183601_filter_category_query' );
function wpse183601_filter_category_query( $query ) {
    // only modify front-end category archive pages
    if( is_category() && !is_admin() && $query->is_main_query() ) {
        $query->set( 'posts_per_page','20' );
        $query->set( 'orderby','meta_value' );
        $query->set( 'meta_key','artwork_title' );
        $query->set( 'order','ASC' );
    }
}

Leave a Comment