I am trying to query any post which has a certain post_object selected as its "parent". The parent value will have to match the ID of the current post. I have been able to replicate this functionality by querying all posts of this post type and then comparing the values within the loop, like so:
<?php
$wp_query = new WP_Query();
$wp_query->query( array (
'post_type' => 'my_post_type',
'meta_key'=>'post_object_field'
));
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php
$parent = get_field('post_object_field');
$parentId = $parent->ID; ?>
<?php if ($postId == $parentId): ?>
// content
<?php endif; ?>
<?php endwhile; endif; ?>
I'm wonder if there is a way to check for this value inside the query, and if so, if it's any faster or more correct.
To get all the posts/pages that are children of a given post/page, you can use the parameter post_parent, using the ID of the parent post.
For example, if you have a post
$wp_query->query( array (
'post_type' => $children_post_type
'post_parent' => $postId
));
And of course, yes, performing a query will be much more efficient than performing a query + getting a field value + creating a variable + looping the results making a comparison...
EDIT: According to your comments, it seems that you're actually trying to get all those posts that have a given value in a custom field of type Post Object. This field contains a number, which is the ID of the post it relates to, so you just need to add a parameter meta_value_num in your query:
$wp_query->query( array (
'post_type' => 'my_post_type',
'meta_key' => 'post_object_field'
'meta_value_num' => $postId
));
This will retrieve all the posts that have a custom field called post_object_field
with a value $postId
.
EDIT: Try this:
$args = array(
'post_type' => 'my_post_type',
'meta_query' => array(
array(
'key' => 'post_object_field',
'value' => $postId,
'compare' => '='
)
)
);
I was able to filter the results within the query using:
<?php
$wp_query = new WP_Query();
$wp_query->query( array (
'post_type' => 'my_post_type',
'meta_query' => array(
array(
'key' => 'post_object_field',
'value' => $postId,
'compare' => '=='
)
)
));
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
// content
<?php endwhile; endif; ?>
<?php
$wp_query = new WP_Query();
$wp_query->query( array (
'post_type' => 'my_post_type',
'meta_query' => array(
array(
'key' => 'post_object_field',
'value' => $postId,
'compare' => '=='
)
)
));
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
// content
enter code here