我需要通过自定义查询在wordpress中获取具有特定类别ID的帖子和精选图片。这是我的问题:
SELECT p.ID, post_title AS title, post_excerpt AS excerpt,t.name AS name_cat ,bb.meta_value AS url_image FROM ap_posts p
LEFT JOIN (
SELECT p1.ID,wm2.meta_value FROM ap_posts p1
LEFT JOIN ap_postmeta wm1 ON ( wm1.post_id = p1.id AND wm1.meta_value IS NOT NULL AND wm1.meta_key = '_thumbnail_id' )
LEFT JOIN ap_postmeta wm2 ON ( wm1.meta_value = wm2.post_id AND wm2.meta_key = '_wp_attached_file' AND wm2.meta_value IS NOT NULL ) ) AS bb ON p.ID = bb.ID
JOIN ap_term_relationships tr ON (p.ID = tr.object_id)
JOIN ap_term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
JOIN ap_terms t ON (tt.term_id = t.term_id) WHERE p.post_type='post' AND p.post_status = 'publish' AND tt.taxonomy = 'category' AND t.term_id =$cat_id ORDER BY post_date DESC
结果还可以,但它运行缓慢,因为我使用了很多“JOIN”。如何优化此SQL以提高性能。感谢
答案 0 :(得分:0)
试试这段代码。,
$args = array(
'post_type'=>'posttype',
'tax_query' => array(
array(
'taxonomy' => 'person', //taxonomy name
'field' => 'name', //category field
'terms' => 'bob' //category name
)
)
);
$query = new WP_Query( $args );
$post_testimonials = $query->posts;
$image= wp_get_attachment_image_src(get_post_thumbnail_id($post_testimonials[0]->ID),'full');
var_dump($image);
使用代码 $ image 变量提供精选图片的网址。循环帖子将进入查询。
答案 1 :(得分:0)
在ap_postmeta
上,将PK更改为PRIMARY KEY(post_id, meta_key)
。