Answers:
global $wp_query;
$args = array(
'category__and' => 'category', //must use category id for this field
'tag__in' => 'post_tag', //must use tag id for this field
'posts_per_page' => -1); //get all posts
$posts = get_posts($args);
foreach ($posts as $post) :
//do stuff
endforeach;
我偶然发现了这个问题,并通过发出MySQL请求解决了该问题。
简而言之:get_post($ args)将为您返回类别= MyCategory 或 tag = MyTag的帖子。
您想要将OR更改为AND。
我的逻辑是直接进行MySQL查询:
我用wpdb代替了query_post();
一些代码 (返回类别为MyCat和标签MyTag的已发布帖子):
$query_byTag="
SELECT wp_posts.ID
FROM wp_posts, wp_term_relationships, wp_terms
WHERE wp_posts.ID = wp_term_relationships.object_id
AND wp_terms.term_id = wp_term_relationships.term_taxonomy_id
AND wp_terms.name = 'MyTag'";
$query_byCat="
SELECT wp_posts.ID
FROM wp_posts, wp_term_relationships, wp_terms
WHERE wp_posts.ID = wp_term_relationships.object_id
AND wp_terms.term_id = wp_term_relationships.term_taxonomy_id
AND wp_terms.name = 'MyCat'";
$query ="
SELECT wp_posts.post_title AS title ,
wp_posts.post_content AS content,
wp_posts.post_date AS blogdate
FROM wp_posts
WHERE wp_posts.post_status = 'publish'
AND wp_posts.ID IN (".$query_byTag.")
AND wp_posts.ID IN (".$query_byCat.")
ORDER BY wp_posts.post_date DESC ";
$result= $wpdb->get_results($query);
这是一种肮脏的方式,但我希望它能帮助您=)
WP_Query
使用tax_query
AND关系可以轻松完成此操作,而无需原始SQL。
此代码有效:
$args = array(
'tag' => get_queried_object()->slug, // If permalink like example.com/tag/example-tag, etc.
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'category', // Taxonomy, in my case I need default post categories
'field' => 'slug',
'terms' => 'interior', // Your category slug (I have a category 'interior')
),
)
); // Get all posts
$posts_new = get_posts( $args );
SELECT wp_posts.post_name
FROM wp_posts, wp_term_relationships, wp_terms, wp_term_taxonomy
WHERE wp_posts.ID = wp_term_relationships.object_id
AND wp_terms.term_id = wp_term_taxonomy.term_id
AND wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id
AND wp_terms.name = "MY TAG"