Support

Account

Home Forums ACF PRO Custom query – return posts with value in custom field

Solving

Custom query – return posts with value in custom field

  • I’ve a CPT with some custom fields – I’m trying to setup a custom query to get all posts of that CPT that actually have a value in the field called: ‘knowledge_field’ – there are 50 posts in that CPT.

    $args = array(
    		'post_type' 	=> 'ze_knowledge',
    		'orderby'       => 'post_date',
    		'order'         => 'DESC',
    		'posts_per_page'=> '-1',
    		'meta_query'		=> array(
    			'key'	=> 'knowledge_field',
    			'compare' => 'EXISTS'
    		)
    	);

    however, whatever I try I’m always getting all posts of that CPT.
    $loop->post_count always shows 50;
    any idea what I’m missing??

  • Hi @mmjaeger

    Could you please try this code?

    $args = array(
    		'post_type' 	=> 'ze_knowledge',
    		'orderby'       => 'post_date',
    		'order'         => 'DESC',
    		'posts_per_page'=> '-1',
    		'meta_query'		=> array(
    			'key'	=> 'knowledge_field',
    			'compare' => '!=',
    			'value' => '',
    		)
    	);

    I hope this helps.

  • thanks James but it doesn’t work – interestingly the following does work:

    $args = array(
    		'post_type' 		=> 'ze_knowledge',
    		'orderby'       	=> 'post_date',
    		'order'         	=> 'DESC',
    		'posts_per_page'	=> '-1',
    		'meta_key'			=> 'knowledge_video',
    		'meta_value'		=> ' ',
    		'meta_compare'		=> '!=',			
    	);
    
  • Hi @mmjaeger

    That’s weird. But I’m glad that you found the solution 🙂

Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Custom query – return posts with value in custom field’ is closed to new replies.