简体   繁体   English

使用meta键获取所有具有自定义字段值的帖子,然后从另一个字段值循环查询结果

[英]Get all posts that have a custom field value with meta key and loop the query results from another field value

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'. 如何获取自定义字段“ wpcf-secret-id-1”中具有相同自定义字段值的自定义帖子类型“文件夹”和“文件”的所有帖子,并且如果有结果,我想显示另一个自定义字段“ 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 最后,我想获取所有第一个自定义字段值与当前帖子相同的帖子,并将结果显示为第二个自定义字段值的循环

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 ? 您是否在数据库中的post_meta表中检查了要查询wpcf-secret-id-1wpcf-secret-id-2的正确密钥? If they are hidden from the backend, they may have an underscore prepended like this: _wpcf-secret-id-1 . 如果它们是从后端隐藏的,则它们可能带有下划线,例如: _wpcf-secret-id-1

Also, your WP_Query usage isnt correct in this case. 同样,在这种情况下,您的WP_Query用法也不正确。 You are overriding the entire Wordpress Loop with $query->the_post(); 您正在使用$query->the_post();覆盖整个Wordpress循环$query->the_post(); and are returning out of the function before resetting it with wp_reset_postdata . 并在使用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.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM