我的问题类似于this one,但现在已经7岁了,所以我想再问一次。
我使用的是get_posts()函数,但是作为's‘参数传递的任何内容似乎只与post标题匹配。例如,此代码只返回标题中包含“向日葵”的帖子,而不返回标签中包含“向日葵”的帖子。
$args = array( 'numberposts' => 99, 's' => 'sunflower');
$postslist = get_posts( $args ); 我刚开始做WP开发,也许我忽略了什么或者使用了错误的函数.任何指点都会非常感谢!
发布于 2022-08-07 19:20:49
IMHO --这比它应该的要复杂得多,但是我设法用以下代码得到了我想要的:
$searchTerm = trim($_REQUEST['search']);
// Get all slugs that are a partial match in tags
$matching_terms_tags = get_terms( array( 'taxonomy' => 'post_tag', 'fields' => 'slugs', 'name__like' => $searchTerm ) );
// Get all slugs that are a partial match in categories
$matching_terms_categories = get_terms( array( 'taxonomy' => 'category', 'fields' => 'slugs', 'name__like' => $searchTerm ) );
// Build taxonomy query
$argsTax = array('numberposts' => 999, 'posts_per_page' => -1, 'nopaging' => true);
$argsTax['tax_query'] = array
(
array
(
'relation' => 'OR',
array ('taxonomy' => 'category', 'field' => 'slug', 'terms' => $matching_terms_categories,'operator' => 'IN',),
array ('taxonomy' => 'post_tag', 'field' => 'slug', 'terms' => $matching_terms_tags, 'operator' => 'IN', ),
),
);
// Get all posts with matching tags and/or matching categories
$postsTax = get_posts($argsTax);
// Also get all posts matching the term, using the regular WP argument 's'
$argsTerms = array('numberposts' => 999, 'posts_per_page' => -1, 'nopaging' => true, 's' => $searchTerm);
$postsSearch = get_posts($argsTerms);
// Merge the 2 result sets and remove duplicates
$postsAll = array_merge($postsSearch, $postsTax);
$postAllNoDupes = array_map("unserialize", array_unique(array_map("serialize", $postsAll)));
foreach ($postAllNoDupes as $post)
{
echo get_the_title($post);
}
wp_reset_query(); 发布于 2022-08-07 16:24:22
另外,要获得以“向日葵”为标记的帖子,您需要添加如下所示的分类参数:
$args = [
'numberposts' => 99,
's' => 'sunflower',
'tax_query' => [
[
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => 'sunflower'
]
]
];
$postslist = get_posts( $args );官方文件:https://developer.wordpress.org/reference/functions/get_posts/
https://stackoverflow.com/questions/73268836
复制相似问题