0
votes

I have a custom post type which lists a set of colours and the types of products they are available on using an ACF repeater.

The intention is to list CPTs with the appropriate available colours on another page. The availability of a colour is set using a custom taxonomy ('availability')

To achieve this I am running a WP_Query() which filters the post type, anda meta_query. This all works fine if I am querying a text sub_field, but I want to run the query on a custom taxonomy.

Based on the examples found here my code is like so:

Functions:

function my_posts_where( $where ) {
    $where = str_replace("meta_key = 'colour_swatch_", "meta_key LIKE 'colour_swatch_", $where);
    return $where;
}
add_filter('posts_where', 'my_posts_where');

On my page:

<?php

$args = array(
    'post_type' => 'colourswatch',
    'meta_query' => array(
        array(
            'key' => 'colour_swatch_%_availability',
            'value' => 'windows',
            'compare' => 'LIKE'
        )
    )
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); 
?>

<p><?php the_title(); ?></p>
<?php
endwhile;
wp_reset_postdata();
?>

This returns back nothing unfortunately, but if I switch 'availability' (the sub_field name for the taxonomy) to 'colour_name' another sub_field I have which is a text field and change the value to 'white' it returns a list of all the colourswatch CPTs featuring white, so I know the basics are working and I assume I have misunderstood how I need to query the taxonomy. Where is this going wrong?

1
is the taxonomy saved as a text in the DB? maybe you need to look for the ID intead?Stender
@Stender I'm not 100%, but my understanding is that it is. The name and slug values both appear to be text. I am hoping to be able to use the name in this case as I ultimately aim to marry it up with the page title.UntitledGraphic
Light bulb moment the value does have to be be the ID, thanks @Stender for the nudge in the right direction.UntitledGraphic
Glad that you solved it!Stender

1 Answers

0
votes

From what I understand for a taxonomy the value must be the ID rather than the name or slug or whatever, so since I need to use the name I need to convert that to the ID. I found that I could do this using get_term_by();

// Get term by name 'windows' in custom taxonomy 'product-types'.
$termId = get_term_by( 'name', 'windows', 'product-types' );

$args = array(
    'post_type' => 'colourswatch',
    'meta_query' => array(
        array(
            'key' => 'colour_swatch_%_availability',
            'value' => $termId->term_id, // translate the term name into its ID
            'compare' => 'LIKE'
        )
    )
);