我写了几个查询,这些查询汇总了按相关帖子分组的下载计数以及其他关系。它们非常适合导出到CSV和WordPress之外的其他用途,但现在我需要在WordPress中编写一些有用的东西。我也在使用Posts-to-Posts插件。
此查询基于直接输入帖子id号返回下载计数和。这在WordPress之外工作得很好。
SELECT r.p2p_from, p.post_title AS Title, SUM(m.meta_value) AS Combined_Totals
FROM wp_postmeta as m
INNER JOIN wp_posts AS p ON p.ID = m.post_id
INNER JOIN wp_p2p AS r ON m.post_id = r.p2p_to
WHERE m.meta_key = \'_download_count\' AND p.post_type=\'dlm_download\'
AND r.p2p_from =\'135\'
我正在尝试编写一个类似于上述查询的函数,但动态显示与当前帖子相关的下载总数,类似于“where ID=current post ID”,我在WP Codex和许多网站中查看过。我以前为WordPress模板编写过模板标签和小函数。但我不知道该怎么写这个。这就是我目前的情况:
public function combined_downloads()
{
global $wpdb;
return $wpdb->get_var(" SELECT SUM( meta_value ) FROM $wpdb->postmeta
LEFT JOIN $wpdb->posts on $wpdb->postmeta.post_id = $wpdb->posts.ID
INNER JOIN \'wp_p2p\' on $wpdb->postmeta.post_id = wp_p2p.p2p_to
WHERE meta_key = \'_download_count\'
AND post_type=\'dlm_download\'
AND post_status = \'publish\'
" );
非常感谢你。
SO网友:TheGentleman
你仍然可以AS
具有$wpdb
, 我发现它仍然让东西看起来更干净。您可以使用$wpdb->prepare()
卫生方法。你在找这样的东西吗?
function combined_downloads($post_id)
{
global $wpdb;
return $wpdb->get_var($wpdb->prepare(
"SELECT SUM( meta_value ) FROM $wpdb->postmeta AS m
LEFT JOIN $wpdb->posts AS p
ON m.post_id = p.ID
INNER JOIN {$wpdb->prefix}p2p AS r
ON m.post_id = r.p2p_to
WHERE m.meta_key = \'_download_count\'
AND p.post_type=\'dlm_download\'
AND p.post_status = \'publish\'
AND r.p2p_from = %d
", $post_id ));
然后可以从循环中调用函数:
$count = combined_downloads($post->ID);
$count
将有查询的结果,您可以在喜欢的地方回显它。如果需要循环外的函数,可以执行以下操作:
$count = combined_downloads($wp_query->post->ID);