Support

Account

Home Forums Add-ons Flexible Content Field How to Query Posts using Flexible Content?

Solved

How to Query Posts using Flexible Content?

  • Hello,

    Sorry if this was answered already.

    I am trying to query a custom post type (“events”) based off of a date created through flexible content. Everything I can find about this topic points to this link: https://www.advancedcustomfields.com/resources/query-posts-custom-fields/
    I’ve been using #4 but it doesn’t work and I’m not sure why. Hopefully someone can help me or point me to the right direction.

    My setup:
    Custom Post Type: events
    Flexible Content Name: the_content
    Layout 1: featured_image
    (within Layout 1) Field Name: start_date

    <?php
    // filter
    function my_posts_where( $where ) {
    	
    $where = str_replace("meta_key = 'featured_image_%", "meta_key LIKE 'featured_image_%", $where);
    
    return $where;
    }
    add_filter('posts_where', 'my_posts_where');
    
    // find todays date
    $date = date('Ymd');
    
    // args
    $args = array(
    	'numberposts'	=> -1,
    	'post_type'	=> 'events',
    	'meta_query'	=> array(
    		array(
    			'key'		=> 'featured_image_%_start_date',
    			'compare'	=> '<=',
    			'value'		=> $date,
    		)
    	)
    );
    
    // query
    $the_query = new WP_Query( $args );

    The following is what shows up for var_dump ($where) and var_dump ($args)
    (var_dump($where) returns null)

    C:\...\wp-content\themes\project\front-page.php:60:null
    
    C:\...\wp-content\themes\project\front-page.php:61:
    array (size=3)
      'numberposts' => int -1
      'post_type' => string 'events' (length=5)
      'meta_query' => 
        array (size=1)
          0 => 
            array (size=3)
              'key' => string 'featured_image_%_start_date' (length=27)
              'compare' => string '<=' (length=2)
              'value' => string '20170104' (length=8)

    What am I doing wrong? I’m not sure why it’s not working. Is $where suppose to return null? Is my_posts_where() suppose to be in functions.php? Any help will be greatly appreciated!

  • Unfortunately, the example number 4 is going to be what most people refer to. There are also many posts on the subject about this if you look. Querying posts by sub fields is a huge PITA and I’ve given up the idea and I look for ways around doing it. I posted an example of working around querying sub pages on a similar topic here https://support.advancedcustomfields.com/forums/topic/get-next-post/ and it might help you.

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

You must be logged in to reply to this topic.