Support

Account

Home Forums General Issues Meta query for post object?

Solved

Meta query for post object?

  • Hi there,

    I am trying to query a post object. I was wondering how this is possible? Can I query with an ID of the associated post?

    Any help would be greatly appreciated.

    Thank you.

  • Hi Christopher.

    What exactly are you trying to achieve?
    You cant query an acf field like you query wp_query since it’s just plain data in an array/string/object.

  • Hi @christopher88

    Can you provide some context? Are you aware of the get_field function and that it will return a formatted value based on the field type.

    For example, if you use get_field to load a post_obect field value, it will return 1 or more post objects.

    Hope that helps.

    Thanks
    E

  • Thanks for your reply Jonathan/Elliot.

    Sorry if my question is confusing. I’m essentially trying to wp query the field. For example, if I was making a simple query to a text field, I would do it like so:

    new WP_Query(array(
    	"meta_key" => "animal",
    	"meta_value" => "cat"
    ));

    But is there a way to query against the associated post? So if I knew post X’s associated ID and I wanted to get all posts associated with post X, how would I go about it?

    Thank you very much for your help.

    Chris

  • Hi @christopher88

    Am i right in assuming that you are using the post_object field? Is this setup as a single or multiple select field?

    Have you tried printing the returned value of get_field()?

  • Hi Elliot

    Thank you for your response.

    Yep I am using the post_object field and it’s set up as a single select field.

    get_field gives me the value of the post I need but my question is how do I query with it? E.g. What would the meta_key be if I want to use it in WP_Query (get all posts with the associated post object ID of X)?

    I have tried the meta query in this tutorial but it doesn’t seem to work for me: http://www.advancedcustomfields.com/resources/tutorials/querying-relationship-fields/

    Thanks again,

    Chris

  • Hi @christopher88

    You can reead up on querying the posts here:
    http://www.advancedcustomfields.com/resources/how-to/how-to-query-posts-filtered-by-custom-field-values/

    Your meta key will need to be the name of the field, and your meta value will need to be the $post_id.

    Hope that helps.

    Thanks
    E

  • Hello all,

    I’m doing a similar thing as above but finding it hard when my post_object has multiple objects.

    OK here is what I am doing:
    1. Custom post type with Courses in
    2. Custom post type with Tutors in
    3. On the Courses page there is a post object box where you select which tutors are deliverying the course.
    4. On the front end, on the single tutors page, it will list the courses this tutor is delivering.

    At the moment on the tutors page I have this:

    <?php 
    $args = array(
    'post_type'		=> 'cpt_courses',
    'posts_per_page'	=> -1,
    'meta_query'		=> array(
    	array(
    		'key' => 'course_tutors',
    		'value' => '86',
    		'compare' => 'IN'
    		)
    	)
    );
    
    // query
    $wp_query = new WP_Query( $args );
    // loop
    while( $wp_query->have_posts() )
    {
    $wp_query->the_post();
    the_title();
    // ...
    }?>

    Help help would be much appreciated, thanks

    Josh

  • Hey everyone,

    Huzzah! Figured it out with this gem:

    http://www.advancedcustomfields.com/resources/tutorials/querying-relationship-fields/

    So from the above all I needed to do was change it to the following:

    <?php 
    $args = array(
    'post_type'		=> 'cpt_courses',
    'posts_per_page'	=> 1,
    'meta_query'		=> array(
    	array(
    		'key' => 'course_tutors',
    		'value' => '"' . get_the_ID() . '"',
    		'compare' => 'LIKE'
    		)
    	)
    );
    
    // query
    $wp_query = new WP_Query( $args );
    
    // loop
    while( $wp_query->have_posts() )
    {
    $wp_query->the_post();
    the_title();
    // ...
    }?>

    Notice the following:

    ‘key’ => ‘course_tutors’,
    ‘value’ => ‘”‘ . get_the_ID() . ‘”‘,
    ‘compare’ => ‘LIKE’

    Finally got there, hope this helps other people! J

  • Hi all, won’t a LIKE query searching for post ID ‘1’ return a row with i.e. ’12’ (a post of ID 12), which would be an error?

    If so, how can we avoid this error?

  • Ah, I see – this is mitigated by the use of quotes:

    array(
    	'key' => 'course_tutors',
    	'value' => '"' . get_the_ID() . '"',
    	...
    )
    
  • This was helpful, and took me awhile to get.
    I’m doing something similar.
    I have a list of staff members as custom post type
    Each staff member makes a monthly book pick – also a custom post type called staffpicks

    ACF is running on staffpicks with a custom object field relating back to the staff member who picked it.

    When using the post object field – even though the post object field will show the title of the post in the select box (which is convenient…thanks), it’s actually saving the post ID of that related post object in the database.

    So when we run the meta query we have to use a value of post id – not the title of that post.

    Am i getting that right?

  • Yes that’s correct. You will want to do the meta query on the posts ID, not the title 🙂

  • I have a similar case, but the key is a User object field called “consultant”. A var_dump of the get_field results in a array of user data.

    Is type of field serialize data too?

    This LIKE compare doesn’t seem to work, but then again neither does the “IN” which I would have thought was the correct compare?

    Details here -> http://stackoverflow.com/questions/26768230/wordpress-meta-query-on-user-object

    Thanks

  • FYI – i just figured out why this does work. The saved value for this field type doesn’t contain the full user object so like compare works if you use userID

  • So this thread has been very helpful! The answer @meandhim provided works great on all my pages, but I am unable to get this to work on my set Posts page – I am only assuming because it is having an issue w/ get_the_ID

    Here is what i’ve got:

    <?php
      $ad_args = array(
        'post_type'       => 'ad',
        'posts_per_page'  => -1,
        'orderby'         => 'rand',
        'meta_query'      => array(
          array(
            'key'     => 'ad_connected_pages',
            'value'   => '"' . get_the_ID() . '"',
            'compare' => 'LIKE'
          )
        )
      );
    
    // query
    $ad_query = new WP_Query($ad_args);
    ?>
    
    <?php if( $ad_query->have_posts() ): ?>
    	<ul>
    	<?php while( $ad_query->have_posts() ) : $ad_query->the_post(); ?>
    		<li>
    			<a href="<?php the_field("ad_url"); ?>">
            <?php $adIMG = get_field("ad_image"); ?>
    				<img src="<?php echo $adIMG['url']; ?>" />
    			</a>
    		</li>
    	<?php endwhile; ?>
    	</ul>
    <?php endif; ?>
    
    <?php wp_reset_query(); ?>
    
  • I have a problem with trying to implement something similar…
    Here is my setup…

    Custom post type : ‘images’
    Custom post type : ‘authors’

    I have a multiple select post_object field on the images edit screen where you can select multiple authors. I have set this to output a post object in the acf edit field group page because I use various fields from the authors on the image display.

    Now I have a filtering option in the images archive and want to be able to query images of a particular author.

    $images_query = new WP_Query([
        'posts_per_page' => -1,
        'post_type' => 'images',
        'meta_query' => array(
            array(
                'key' => 'author',
                'value' => get_query_var('author'),
                'compare' => 'LIKE'
            ),
        )
    ]);

    I have got everything working without the meta_query so it’s not a loop problem, but nothing is showing up from my output loop when I add the meta_query.

    Does anyone know if the problem is due to my acf output being a post object rather than a post id? Please advise.

  • Two things you can try:

    1. value does accept an arra so that may help matching on a post_object -> ‘value’ => array(‘auth1′,’auth2’),
    2. Ensure the key author matches the query_var type. e.g. if author is name you may need to convert it to ID etc.

    Basically check what exact data the AFC field is saving… It’s not always what you expect because the AFC output is an abstracted version of the data and not the raw values which meta_query uses for matching. Look at author key->values in the DB or var_dump using get_post_meta not get_field.

  • PS. as per my question above in this tread. I was expecting the output of the met_query to be a full user_object but the key was just an ID. AFC builds the user object from the stored ID when get_field is called. I bet your issue is similar.

  • Oh dear. I just realised that my author field (multiple select post_object field) is a subfield of a group… How can I deal with this?

  • My fields are as follows: authors is a group field and within that I have a subfield of people (amongst other subfields). People is a multiple post_object select field.

    I have the impression from this thread that it is possible to query subfields in this way…

    $images_query = new WP_Query([
        'posts_per_page' => -1,
        'post_type' => 'images',
        'meta_query' => [
            [
                'key' => 'authors_%_people',
                'value' => ['85'],
                'compare' => 'IN'
            ],
        ],
    ]);

    It is not working, please could you advise me.

  • Have a read of this post, Section 4 to be precise: https://www.advancedcustomfields.com/resources/query-posts-custom-fields/

    In order to use a % wildcard you need to create a custom field for this query.

    See if that works for you.

  • I have now read section 4 of that article, but I don’t really understand it because I’m not too hot on mySQL. But either way, I’ve added the following to my functions file :

    function my_posts_where( $where ) {
        global $wpdb;
        $where = str_replace(
                  "meta_key = 'authors_", 
                  "meta_key LIKE 'authors_",
                  $wpdb->remove_placeholder_escape($where)
        );
        return $where;
    }
     
    add_filter('posts_where', 'my_posts_where');

    and I’m trying to query like this …

    $images_query = new WP_Query([
        'posts_per_page' => -1,
        'post_type' => 'images',
        'meta_query' => [
            [
                'key' => 'authors_%_people',
                'compare' => '='
                'value' => ['85'],
            ],
        ],
    ]);

    Any ideas why this wouldn’t be working? Could it be because I allow multiple values in the people post_object field?

    What do you mean by “create a custom field for this query”?

  • Oh so you Authors is a repeater and in that you have a multiple select post object that is People? If so try this:

    $images_query = new WP_Query([
        'posts_per_page' => -1,
        'post_type' => 'images',
        'meta_query' => [
            [
                'key' => 'authors_%_people',
                'compare' => 'LIKE'
                'value' => '"'.85.'"',
            ],
        ],
    ]);
Viewing 25 posts - 1 through 25 (of 33 total)

The topic ‘Meta query for post object?’ is closed to new replies.