Support

Account

Home Forums ACF PRO Check posts for Custom Field

Solved

Check posts for Custom Field

  • Hi

    I am trying to display an Image Slider which fetches featured image and excerpt from any pages or posts that have a custom field checked to true.

    I’ve tried this code here: http://www.advancedcustomfields.com/resources/true-false/ with no luck.

    My custom field is a checkbox, that when clicked should add the page or post to the Image Slider. My field name is: ‘display_in_carousel’

    How do I modify the code in the example linked above to meet my requirements?

    Many Thanks

  • try something like this:

    <ul class="slider">
    <?php if( get_field('display_in_carousel') )
    {
    $image = get_field('image'); 
    if( !empty($image) ): ?>
    	<li><img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" /></li>
    <?php endif; 
    }
    else
    {
        //do nothing
    }
    ?>
    </ul>

    of course you need to wrap that like your slider need it (and probably change way of load image too)

    or you do it with meta-query like the other part of the example

  • Hi

    Sorry; that’s not the bit i’m stuck on.
    It’s the actual meta_query loop that doesn’t appear to be working. I’m just wondering if my ‘value’ & ‘compare’ values are correct?

    /*
    * Query posts for a true/false value.
    * This method uses the meta_query param to match the string “1” to the database value “1|0”
    */

    $posts = get_posts(array(
    	'meta_query' => array(
    		array(
    			'key' => 'field_name',
    			'value' => '1',
    			'compare' => '=='
    		)
    	)
    ));
    
    if( $posts )
    {
    	foreach( $posts as $post )
    	{
    		setup_postdata( $post );
    
    		// ...
    
    	}
    
    	wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly
    }

    What should my value and compare values be?

    Thanks

  • as far as i understand the array should be:

    array(
    			'key' => 'display_in_carousel',
    			'value' => '1',
    			'compare' => '='
    		)

    because true/false should have value 1/0, compare should maybe = instead of == (i am not sure, try out both and one should work)
    i dont work long time with wordpress, that’s why i am not that familiar with meta_query

  • I ended up using this which worked:

    
    		<?php 
    		
    		$posts = get_posts(array(
    			'numberposts'	=> -1,
    			'post_type'		=> 'page',
    			'meta_key'		=> 'display_in_carousel',
    			'meta_value'	=> '1'
    		));
    		
    		if( $posts ): ?>
    
    			<?php foreach( $posts as $post ): 
    				
    				setup_postdata( $post )
    				
    				?>
    
    			<?php endforeach; ?>
    			
    			
    			<?php wp_reset_postdata(); ?>
    		
    		<?php endif; ?>
Viewing 5 posts - 1 through 5 (of 5 total)

The topic ‘Check posts for Custom Field’ is closed to new replies.