dongshu4221 2014-10-16 11:59
浏览 93

使用自定义分类法自定义SQL查询(Wordpress)

I use the following SQL query to fetch custom posts in Wordpress. I ended up with this solution because i needed to fetch und sort the posts based on custom meta data. This woks pretty well so far!

But how do i incorporate custom taxonomies in my query? Say for example only fetch posts that are associated with term_id 5? I'm really stuck here cause i can't figure out how wp_terms, relations etc are connected...

Any help is greatly appreciated!

UPDATE: After some reading the solution in my case is this:

WordPress stores the relations between taxonomies and posts in wp_term_relationships (where object_id is the post_id and term_taxonomy_id ist the term_id in wp_terms). So if i want to only fetch posts that belong to a specific term_id, i came up with the following query. Seems to work as far as i can tell!

This is my query

global $wpdb;
$activelang = ICL_LANGUAGE_CODE;
$cmonth = date('Y-m');

$myquery = "
SELECT wposts.*, wpostmeta.meta_value AS date
  FROM wp_posts wposts, wp_postmeta wpostmeta, wp_icl_translations wicl_translations, , wp_term_relationships wptermrelations
  WHERE wposts.post_status = 'publish'
  AND wpostmeta.post_id = wposts.ID
  AND (wptermrelations.object_id = wposts.ID AND (wptermrelations.term_taxonomy_id = '29' OR wptermrelations.term_taxonomy_id = '30'))
  AND wposts.post_type = 'event'
  AND wicl_translations.element_id = wposts.ID
  AND wicl_translations.language_code = '$activelang'
  AND (wpostmeta.meta_key = '_ws_prem_date' OR wpostmeta.meta_key = '_ws_date1_date' OR ... ... OR wpostmeta.meta_key = '_ws_date10_date') 
  AND wpostmeta.meta_value >= '$cmonth-01'
  ORDER BY CAST(date AS DATETIME),wposts.post_title ASC
  ";

$myloop = $wpdb->get_results($myquery);

In case someone is wondering what this query does:

This query fetches custom post types (events that have multiple dates associated) and builds a loop for these events that allows for duplicate entries since a 'normal' WordPress loop always filters out any duplicate entries.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 西门子S7-Graph,S7-300,梯形图
    • ¥50 用易语言http 访问不了网页
    • ¥50 safari浏览器fetch提交数据后数据丢失问题
    • ¥15 matlab不知道怎么改,求解答!!
    • ¥15 永磁直线电机的电流环pi调不出来
    • ¥15 用stata实现聚类的代码
    • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
    • ¥20 docker里部署springboot项目,访问不到扬声器
    • ¥15 netty整合springboot之后自动重连失效
    • ¥15 悬赏!微信开发者工具报错,求帮改