获取自定义字段键的所有值(交叉发布)
-
-
似乎您将其用作分类法.为什么不在保存时简单地(自动)在这些帖子中添加术语?使查询变得容易得多.Seems like you're using this as a taxonomy. Why not simply (automatically) add a term to these posts when saving? Would make querying a lot easier.
- 5
- 2011-02-15
- kaiser
-
@kaiser我非常感谢您成为天才!@kaiser I can't thank you enough for being a genius!
- 0
- 2016-10-26
- user2128576
-
7 个回答
- 投票数
-
- 2011-02-15
一种可能的方法是使用WPDB类中的辅助方法之一来执行更精细的基于元的查询.但是,使用其中一些功能的警告是,即使您只调用一列或一行,您通常也不需要获取简单的数据数组,并且通常不必对对象属性进行不必要的引用.>
当然,并非所有功能都是相同的,
WPDB 方法get_col
有针对性地提及,该方法返回一个简单的平面数组.数据查询中,我之所以特别提及,是因为以下示例将调用此方法.WordPress-WPDB选择数据列
$ wpdb->get_col()这是一个示例函数,该函数在数据库中查询所选帖子类型,帖子状态以及特定元键(或技术性较差的自定义字段)的所有帖子.
function get_meta_values( $key = '', $type = 'post', $status = 'publish' ) { global $wpdb; if( empty( $key ) ) return; $r = $wpdb->get_col( $wpdb->prepare( " SELECT pm.meta_value FROM {$wpdb->postmeta} pm LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id WHERE pm.meta_key = %s AND p.post_status = %s AND p.post_type = %s ", $key, $status, $type ) ); return $r; }
例如,如果您想找出哪些帖子的元键为 rating ,则对于该帖子类型 电影 > ,而您想将该信息存储在变量中,则这样的调用的示例是.
$movie_ratings = get_meta_values( 'rating', 'movies' );
如果您只想将数据打印到屏幕上,PHP的implode函数可以将简单的数组快速拼接成数据行.
// Print the meta values seperate by a line break echo implode( '<br />', get_meta_values( 'YOURKEY' ));
例如,通过对返回的数据进行简单循环并构建计数数组,您还可以使用返回的数据来算出具有这些元值的帖子数.
$movie_ratings = get_meta_values( 'rating', 'movies' ); if( !empty( $movie_ratings ) ) { $num_of_ratings = array(); foreach( $movie_ratings as $meta_value ) $num_of_ratings[$meta_value] = ( isset( $num_of_ratings[$meta_value] ) ) ? $num_of_ratings[$meta_value] + 1 : 1; } /* Result: Array( [5] => 10 [9] => 2 ) // ie. there are 10 movie posts with a rating of 5 and 2 movie posts with a rating of 9. */
该逻辑可以应用于各种数据,并且可以扩展为以多种不同方式工作.因此,我希望我的例子对您有所帮助,并且简单易懂.
One possible approach would be to use one of the helper methods in the WPDB class to do a more refined meta based query. The caveat to using some of these functions however, is that you don't usually get back a simple array of data and usually have to make needless references to object properties, even if you're only calling for one column or row.
Of course, not all functions are the one and the same, and a purposeful mention goes out to the WPDB method,
get_col
which returns a simple flat array of the data queried for, i make this mention specifically because the example following will call upon this method.WordPress - WPDB Selecting a column of data
$wpdb->get_col()Here's an example function which queries the database for all posts of a chosen post type, post status and with a specific meta key(or custom field to the less technically minded).
function get_meta_values( $key = '', $type = 'post', $status = 'publish' ) { global $wpdb; if( empty( $key ) ) return; $r = $wpdb->get_col( $wpdb->prepare( " SELECT pm.meta_value FROM {$wpdb->postmeta} pm LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id WHERE pm.meta_key = %s AND p.post_status = %s AND p.post_type = %s ", $key, $status, $type ) ); return $r; }
So for example, if you like to find out which posts have a meta key of rating, for the post type movies and you'd like to store that information inside a variable, an example of such a call would be..
$movie_ratings = get_meta_values( 'rating', 'movies' );
If you wanted to do nothing more than print that data to screen, PHP's implode function can quickly splice that simple array into lines of data.
// Print the meta values seperate by a line break echo implode( '<br />', get_meta_values( 'YOURKEY' ));
You can also use the returned data to work out how many posts have these meta values by doing a simple loop over the returned data and building an array of the counts, for example.
$movie_ratings = get_meta_values( 'rating', 'movies' ); if( !empty( $movie_ratings ) ) { $num_of_ratings = array(); foreach( $movie_ratings as $meta_value ) $num_of_ratings[$meta_value] = ( isset( $num_of_ratings[$meta_value] ) ) ? $num_of_ratings[$meta_value] + 1 : 1; } /* Result: Array( [5] => 10 [9] => 2 ) // ie. there are 10 movie posts with a rating of 5 and 2 movie posts with a rating of 9. */
This logic could be applied to various kinds of data, and extended to work any number of different ways. So i hope my examples have been helpful and simple enough to follow.
-
如果您只想提取"唯一"元值,那么对于将来的查看者也很有趣-您可以在上面的函数中的" SELECT"之后直接输入" DISTINCT".可能有用.Also fun-fact for future viewers, if you want to pull only Unique meta values - you type `DISTINCT` right after the `SELECT` in the function above. Could be useful.
- 3
- 2014-02-07
- Howdy_McGee
-
我认为这非常有用I think this is extremely useful
- 0
- 2017-05-01
- Pablo S G Pacheco
-
如何执行此操作,并返回排序后的值?,我认为使用ORDERby,但无法弄清楚如何使用它How to do this, and return the values sorted?, I think that using ORDER by but I cant figure out how to use it
- 0
- 2018-04-17
- efirvida
-
-
我可以想象有多个具有相同值的元值是有效的情况,因此没有在我的代码中添加该值.如果您想要独特的价值,那将是您的最佳选择.另外,您还可以将其添加为函数的参数(因此,可以根据需要使用或不使用它).I can imagine cases where it would be valid to have multiple meta values of the same value, and thus didn't not make that addition to my code. If you want distinct values, this would be the way to go though. Additionally you could also add that in as an argument for the function(so you can use it or not, as appropriate).
- 1
- 2014-01-24
- t31os
-
-
- 2015-10-03
使用全局$ wpdb不好或不需要:
// function to grab all possible meta values of the chosen meta key. function get_meta_values( $meta_key, $post_type = 'post' ) { $posts = get_posts( array( 'post_type' => $post_type, 'meta_key' => $meta_key, 'posts_per_page' => -1, ) ); $meta_values = array(); foreach( $posts as $post ) { $meta_values[] = get_post_meta( $post->ID, $meta_key, true ); } return $meta_values; } $meta_values = get_meta_values( $meta_key, $post_type );
It is not good or needed to use the global $wpdb:
// function to grab all possible meta values of the chosen meta key. function get_meta_values( $meta_key, $post_type = 'post' ) { $posts = get_posts( array( 'post_type' => $post_type, 'meta_key' => $meta_key, 'posts_per_page' => -1, ) ); $meta_values = array(); foreach( $posts as $post ) { $meta_values[] = get_post_meta( $post->ID, $meta_key, true ); } return $meta_values; } $meta_values = get_meta_values( $meta_key, $post_type );
-
在大多数情况下,这是我首选的方法.它会进行五个查询,而不仅仅是一个查询,但是,由于它使用标准的WordPress过程来生成和提交查询,因此任何特定于平台的缓存(例如WP Engine的对象缓存或某些随机插件)都将启动.数据还将在请求期间将其存储在WordPress的内部缓存中,因此,如果需要,无需再次从数据库中检索.This would be my preferred method of doing it, in most cases. It makes five queries, rather than just one, but, as it's using the standard WordPress procedures to generate and submit them, any platform-specific caching (such as WP Engine's Object Caching or some random plugin) will kick in. The data will also be stored in WordPress' internal cache for the duration of the request, so will not need to be retrieved from the database again, if needed.
- 0
- 2017-06-02
- Andrew Dinmore
-
任何过滤器也将应用于数据,这在例如多语言站点上可能非常重要.最后,由于它仅使用标准的WordPress核心功能,因此将来更新可能会破坏它的可能性很小.Any filters will also be applied to the data, which could be extremely important on, for example, a multi-lingual site. Lastly, since it's using just standard WordPress core functions, it's much less likely to be broken by a future update.
- 0
- 2017-06-02
- Andrew Dinmore
-
通过将查询限制为发布ID,可以提高性能. 添加:''fields'=>'ids'` 因此,查询数组如下所示: 数组 'post_type'=> $post_type, 'meta_key'=> $meta_key, 'posts_per_page'=> -1, 'fields'=>'ids' )```This might be made more performant by limiting the query to post id? Add: `'fields' => 'ids'` So, the query array would look like: ```array( 'post_type' => $post_type, 'meta_key' => $meta_key, 'posts_per_page' => -1, 'fields' => 'ids' )```
- 1
- 2020-04-13
- Pea
-
注意,这还会滤除仅在未发布的帖子中存在的元值,因此请确保使用"post_status" arg将此功能设置为不是错误Caution this also filters out meta values that exist only on not published posts so make sure you use the 'post_status' arg to make this a feature not a bug
- 0
- 2020-07-23
- jnhghy - Alexandru Jantea
-
- 2011-02-15
最快的方法是自定义sql查询,我不确定,但是您可以尝试
$wpdb->get_results(" SELECT posts.* , COUNT(*) 'moodcount' FROM $wpdb->posts as posts JOIN $wpdb->postmeta as postmeta ON postmeta.post_id = posts.ID AND postmeta.meta_key = 'Mood' GROUP BY postmeta.meta_key ");
如果有的话,那就开始了.
the fastest way would be a custom sql query and i'm not sure but you can try
$wpdb->get_results(" SELECT posts.* , COUNT(*) 'moodcount' FROM $wpdb->posts as posts JOIN $wpdb->postmeta as postmeta ON postmeta.post_id = posts.ID AND postmeta.meta_key = 'Mood' GROUP BY postmeta.meta_key ");
If anything then its a start.
-
谢谢,但是难道不应该不惜一切代价避免自定义查询吗?我更喜欢使用WP抽象层(这就是所谓的吗?)……但是当然,如果这不可能的话.thanks, but shouldn't custom quesries be avoided 'at all cost'? I'd prefer to use the WP abstraction layer (is that what it's called?)... but of course if this is not possible..
- 1
- 2011-06-08
- mikkelbreum
-
如果以正确的方式编写自定义查询,则可能会更好,并且只有在不知道自己在做什么的情况下才应避免使用它们.Custom queries, if written the right way, can be better and you should only avoid them if you don't know what you're doing.
- 0
- 2011-06-08
- Bainternet
-
我同意mwb .custom查询非常有用且实用,但我认为它们在数据库上也要重得多.尤其是使用SRT函数时.I Agree with mwb .custom queries are very usefull and practical, but I think they are also much heavier on the DB.. especially using SRT functions..
- 1
- 2011-12-10
- krembo99
-
- 2013-09-07
用于通过meta键获取所有meta值
$values = $wpdb->get_col("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = 'yourmetakey'" );
For getting all meta values by a meta key
$values = $wpdb->get_col("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = 'yourmetakey'" );
-
这种方法的问题是缺乏特异性,您会从这种查询中获得大量结果,其中可能包括草稿,已删除邮件,帖子,页面以及任何其他现有的帖子类型.您永远不应该查询不需要的内容,在这里肯定需要特殊性.The issue with this approach is the lack of specificity, you'll get numerous results from such a query, which could include drafts, trashed items, posts, pages, and any other post type that exists. You should never query for what you don't need, specificity is most certainly required here.
- 3
- 2014-01-24
- t31os
-
虽然确实可以从其他帖子类型和状态获取值,但有时您所需要的只是这些值,并且除了需要的地方没有使用过meta_key.如果所有/大多数值都是唯一的,则这可能是最佳解决方案.While it is true that you could get values from other post types and statuses, there are times when all you need are the values and you haven't used that meta_key anywhere but where you need it. If all/most values are unique, this may be the best solution.
- 0
- 2018-06-23
- Luke Gedeon
-
- 2012-01-31
没有理由不能将t31os和Bainternet的代码合并为一个可重用的准备好的语句(wordpress样式),该语句可以通过一次有效的操作返回计数和值.
这是一个自定义查询,但仍在使用wordpress数据库抽象层-因此,例如,表名到底是什么或它们是否更改都无关紧要,并且这是一个准备好的语句,因此我们可以安全得多SQL攻击等
在这种情况下,我不再检查帖子类型,而是排除空字符串:
$r = $wpdb->get_results( $wpdb->prepare( " SELECT pm.meta_value AS name, count(*) AS count FROM {$wpdb->postmeta} pm LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id WHERE pm.meta_key = '%s' AND pm.meta_value != '' AND p.post_type = '%s' GROUP BY pm.meta_value ORDER BY pm.meta_value ", $key, $type) ); return $r;
特别是
这将返回一个对象数组,如下所示:
array 0 => object(stdClass)[359] public 'name' => string 'Hamish' (length=6) public 'count' => string '3' (length=1) 1 => object(stdClass)[360] public 'name' => string 'Ida' (length=11) public 'count' => string '1' (length=1) 2 => object(stdClass)[361] public 'name' => string 'John' (length=12) public 'count' => string '1' (length=1)
There's no reason why you can't merge t31os and Bainternet's code to have a reusable prepared statement (wordpress style) that returns the count and the values in one efficient operation.
It's a custom query but it's still using the wordpress database abstraction layer - so for example it doesn't matter what the table names really are, or if they change, and it's a prepared statement so we're that much safer from SQL attacks etc.
In this instance I'm no longer checking for post type and I'm excluding empty strings:
$r = $wpdb->get_results( $wpdb->prepare( " SELECT pm.meta_value AS name, count(*) AS count FROM {$wpdb->postmeta} pm LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id WHERE pm.meta_key = '%s' AND pm.meta_value != '' AND p.post_type = '%s' GROUP BY pm.meta_value ORDER BY pm.meta_value ", $key, $type) ); return $r;
In this particular is
This will return an array of objects like so:
array 0 => object(stdClass)[359] public 'name' => string 'Hamish' (length=6) public 'count' => string '3' (length=1) 1 => object(stdClass)[360] public 'name' => string 'Ida' (length=11) public 'count' => string '1' (length=1) 2 => object(stdClass)[361] public 'name' => string 'John' (length=12) public 'count' => string '1' (length=1)
-
-
请注意,如果未指定post_id,则默认为当前帖子.Note that this defaults to the current post, when no post_id is specified.
- 0
- 2017-07-29
- birgire
-
我知道如何获取特定帖子的自定义字段值.
我需要获取与特定自定义帖子键相关的所有值,所有帖子.
有人知道这样做的有效方法吗?我不想遍历数据库中的所有帖子ID.
示例:
4为名为" Mood"的自定义字段发布了所有具有不同值的值. 2个帖子的值为" happy",1个帖子的值为" angry",1个帖子的值为" sad"
我想输出:在我们所有的帖子中:两个快乐,一个愤怒和一个悲伤的作者.
但是很多帖子.
我要找的是: