0
votes

I have an issue that is doing my head in, I'm trying to sort my posts using pre_get_posts by and ACF field that is a text field.

Here is my code:

function my_pre_get_posts( $query ) {

    // do not modify queries in the admin
    if( is_admin() ) {

        return $query;

    }

    if( $query->is_main_query() && $query->is_tax('locations')) {

        $query->set('meta_key', 'level');
        $query->set('orderby', 'meta_value');
        $query->set('order', 'DESC');

    }   

    // return
    return $query;

}

add_action('pre_get_posts', 'my_pre_get_posts');

In the ACF config, it's set to text and the values of this text can be Bronze, Silver, Gold etc.

UPDATE I've now changed the level field to a number and switch it round 1 = Bronze, 2 = Silver etc.

Still, I get nothing.

When I run the below nothing gets returned.

Any ideas?

2

2 Answers

0
votes

I think you could be inadvertently overwriting the whole query. Try this (untested) snippet:

function my_pre_get_posts( $query ) {
    if( ! is_admin() && $query->is_main_query() && $query->is_tax('locations')) {
        $query->set('meta_key', 'level');
        $query->set('orderby', 'meta_value');
        $query->set('order', 'DESC');
    }
}
add_action('pre_get_posts', 'my_pre_get_posts');

Note that $query is not returned.

Good luck!

0
votes

So in the end of switched it from the functions.php file to the taxonomy template.

Here is my finished code:

<?php

if(isset($_GET['type'])) {
    if($_GET['type'] == 'villa') {
        $filter = array(
                'key'     => 'type_name',
                'value'   => 'Villa',
                'compare' => '=',
            );
    } elseif ($_GET['type'] == 'apartment') {
        $filter = array(
                'key'     => 'type_name',
                'value'   => 'Apartment',
                'compare' => '=',
            );
    } elseif ($_GET['type'] == 'alls') {
        $filter = array(
            'relation' => 'or',
            array(
                'key'     => 'type_name',
                'value'   => 'Villa',
                'compare' => '=',
            ),
            array(
                'key'     => 'type_name',
                'value'   => 'Apartment',
                'compare' => '=',
            )
        );
    }
}

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
    'post_type' => 'properties',
    'post_per_page' => 12,
    'paged' => $paged,
    'meta_key' => 'level',
    'orderby' => 'meta_value',
    'order' => 'DESC',
    'tax_query' => array(
        array(
            'taxonomy' => 'locations',
            'field'    => 'slug',
            'terms'    =>  $term->slug,
        ),
    ),
    'meta_query' => $filter
);
// the query
$the_query = new WP_Query( $args ); ?>

Fingers crossed it helps someone else.