admin管理员组文章数量:1122846
Im looking to count how many meta keys exist within a post, because each time a specific user action happens, a new meta key is created with a date in it.
I have this, which does not return anything (I'm looking for a number)...
...
$post_title = $row->post_title;
$id = $row->ID;
$post_count = $wpdb->get_var("
SELECT COUNT(DISTINCT $wpdb->postmeta.meta_key) FROM $wpdb->posts
LEFT JOIN $wpdb->postmeta
WHERE $wpdb->posts.post_type = 'things'
AND $wpdb->postmeta.meta_key = 'dates'
AND post_id = $id
");
echo $post_title . ' (' . $post_count . ')' . "\n";
}
Similarly, I'd like to count the number of meta keys in total related to a custom post, any help on either of these would be greatly appreciated!
Im looking to count how many meta keys exist within a post, because each time a specific user action happens, a new meta key is created with a date in it.
I have this, which does not return anything (I'm looking for a number)...
...
$post_title = $row->post_title;
$id = $row->ID;
$post_count = $wpdb->get_var("
SELECT COUNT(DISTINCT $wpdb->postmeta.meta_key) FROM $wpdb->posts
LEFT JOIN $wpdb->postmeta
WHERE $wpdb->posts.post_type = 'things'
AND $wpdb->postmeta.meta_key = 'dates'
AND post_id = $id
");
echo $post_title . ' (' . $post_count . ')' . "\n";
}
Similarly, I'd like to count the number of meta keys in total related to a custom post, any help on either of these would be greatly appreciated!
Share Improve this question asked Jul 19, 2012 at 5:00 marctainmarctain 5673 gold badges8 silver badges19 bronze badges3 Answers
Reset to default 0You have a structural problem with your data. Serialized data in the database is terrible if you need to search over pieces of that serialized data.
There is no reliable, efficient, and certainly no easy, SQL query to search over serialized data. "serialization" is a PHP mechanism. It isn't SQL. To the database that is just a string. Your only SQL choice is a regex on the string. WP_Query certainly won't do it. That functionality is not built in, probably for the reason listed above. Iterating over the data is about the only solution you have given the data structure you are dealing with.
However, the correct solution in my opinion is to alter your data structure so that you are saving granular pieces of data in the database. In other words, use a lot of different keys for the values that you need to search over.
You can simply do : count( get_post_custom_keys($pid) )
I solved this problem with some more trial and error:
This got me the # of post meta with the correct id,
...
$post_title = $row->post_title;
$id = $row->ID;
$post_count = $wpdb->get_var("
SELECT COUNT(*) FROM $wpdb->postmeta
WHERE post_id = $id
本文标签: countCounting number of identical meta keys
版权声明:本文标题:count - Counting number of identical meta keys 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736284810a1927329.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论