questions

How to specify a query for a custom post type using the selector advanced custom field?

Rate this post

I’m trying to filter through my ‘Campaigns’ custom post type and only display the post which has the select advanced custom fields set to ‘Featured Campaign’. The select acf can only have a value of ‘Featured Campaign’ or ‘Not a Featured Campaign’

So far this is my code, but instead of displaying the ‘Campaign’ with the ‘Featured Campaign’ select, it shows the most recently uploaded ‘Campaign’

Any help would be appreciated. Thanks in advance!

<?php
    $args = array(
        'posts_per_page' => 1,
        'post_status' => 'publish',
        'post_type' => 'campaigns',
        'meta_query' => array (
             'key' => 'featured',
             'value' => 'Featured Campaign'
        )
    );
    query_posts( $args );
    if (have_posts()) :
        while (have_posts()) : the_post();
            ?>
            <div class="post">
                <?php the_post_thumbnail(); ?>
                <h3 class="post__title heading--primary u-uppercase"><?php the_title(); ?></h3>
                <p class="text-color--primary"><?php the_field(campaign_category); ?></p>
            </div>
        <?php
        endwhile;
        wp_reset_query();
    endif;
    ?>

 

✔️Solution:

Thanks to CBroe in the comments section, the answer is as follows:

meta_query expects nested arrays, even in the case of one query. The $args array has been changed to and now works as expected:

$args = array(
    'posts_per_page' => 1,
    'post_status' => 'publish',
    'post_type' => 'campaigns',
    'meta_query' => array (
        array (
            'key' => 'featured',
            'value => 'Featured Campaign'
        )
    )
);

Leave a Reply

Your email address will not be published.

Back to top button