0

I'm using the Advanced Custom Field (ACF) plugin in a Custom Post Type (CPT).

I have field group in ACF that contains a Image field and true/false field called 'home_offer'.

I'm using this ACF in a Custom Post Type called Offers.

I want to loop through the CPT Offers and check if the true/false field 'home_offer' is checked.

How do I check if the true/false field is selected.

Ive started with this WP_Query.

    <div id="offers">
            <?php
                $offers_args = array(
                    'post_type' => 'Offers',
                    'post_per_page' => 1,
                    'meta_query' => array(
                            array(
                                'key'       => 'home_offer',
                                'value'     => 'on',
                                'compare' => '=', 
                                'type'      => 'CHAR'
                            );
                    );
                );

                $offers_loop = new WP_Query($offers_args);

                if($offers_loop->have_posts()):
                    while($offers_loop->have_posts()):
                        $offers_loop->the_post();

                $image = get_field('image');        

            ?>

            <div id="offerLeft">

                <img src="<?php echo $image ?>" alt="" />

            </div>  

            <?php

                endwhile;
                endif;

                wp_reset_postdata();

            ?>

        </div>

2 Answers 2

4

First of all, 'post_per_page' => 1 in your code is wrong, right name of the argument is posts_per_page (note the plural in postS_per_page)

then if you want query for a 'true/false' field in ACF you have to use

'meta_query' => array(
  array(
    'key' => 'home_offer',
    'value' => '1',
    'compare' => '=='
  )
)

See ACF docs

0

The following code works for WordPress >= 3.5 (source). I couldn't get it to work the ACF way. No need to use 'meta_query' this way. Just replace 'meta_query' with the following two lines to offer_args and and it should work.

'meta_key'     =>   'home_offer',
'meta_compare' =>   'EXISTS', // or 'NOT EXISTS' if no offer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.