WP Query taxonomy in two different custom fields

[ad_1]

Hi,

As you use the taxonomy_advanced field, the value of terms will be saved in custom fields. So you can’t use tax_query in this case. Only meta_query works.

I think the 2nd query is close. Please try this:

'meta_query' => [
    [
        'key' => 'published',
        'value' => '10',
    ],
],

This will show all books that have a custom field published with value 10, which means getting all books published by “max” in this case.

The problem is that if you choose multiple publishers, then the value is like 10,11,15 (comma-separated string), then using the above query only get books belong to one publisher.

In this case, I’d suggest using compare param to make WordPress expand the operation. By default (when obmiting like above, it’s =). We can use LIKE as follows:

Using LIKE:

'meta_query' => [
    [
        'key' => 'published',
        'value' => '10',
        'compare' => 'LIKE',
    ],
],

This will match 10, 10,11,15 (correct) but also match 100, 11,101,12 (incorrect). So, after getting those books, you need to check the value again, like this:

$query = new WP_Query( $args ); // your query args, which includes meta query above
while ( $query->have_posts() ) {
    $query->the_post();
    $published = rwmb_meta( 'published' );
    $published_ids = wp_list_pluck( $published, 'term_id' );
    if ( in_array( 10, $published_ids ) ) {
        // Output book here
    }
}

This is not optimal, but still does the job. You just get more books than you needs in some case, but you can verify them later.

WP_Query also supports REGEXP in compare parameter, but I haven’t used it. If you know it with MySQL (here is a tutorial I found), then you might want to try it.

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer