how can i get all posts of both custom post type 'folder' and 'file' that have the same custom field value in custom field 'wpcf-secret-id-1' and in case if there are results i would like to show the value of another custom field 'wpcf-secret-id-2'.
I have tried following code but seems not to work:
function get_all_post_from_field_value($postid)
{
$args = array(
'post_type' => array(
'folder', 'file'
),
'meta_query' => array(
array(
'key' => 'wpcf-secret-id-1',
'value' => ( $postid )
)
)
);
// The Query
$query = new WP_Query($args);
// The Loop
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
// I am not sure how to get the field value of 'wpcf-secret-id-2'
return get_post_field('wpcf-secret-id-2');
}
}
}
add_shortcode( 'get-posts-by-field-value', 'get_all_post_from_field_value');
I would like at the end to get all posts where first custom field value is the same of current post and show the results as a loop of the second custom field value
</div>
Looks like it should work, I don't see anything obviously wrong with your query.
The only thing that may be happening is: are these custom fields hidden? Have you looked in your post_meta table in your database to check the correct key to be querying for wpcf-secret-id-1
and wpcf-secret-id-2
? If they are hidden from the backend, they may have an underscore prepended like this: _wpcf-secret-id-1
.
Also, your WP_Query usage isnt correct in this case. You are overriding the entire Wordpress Loop with $query->the_post();
and are returning out of the function before resetting it with wp_reset_postdata.
A better way to do that would be:
$query = new WP_Query($args);
if ($query->found_posts > 0) {
$post = $query->posts[0];
return get_post_meta($post->ID, 'wpcf-secret-id-2', true);
}
else
{
return ""; //Good habit: if you are returning some value, make sure you always return *something*, even when there is no value to return.
}