在过去的两天里,我一直在努力实现这一目标,但没有任何效果。我正在尝试构建通过标记搜索任何帖子、页面和一些其他自定义帖子类型的功能。我创建了一个插件,它注册了一个名为search\\u tag的分类法。
search-tags.php
require_once __DIR__ . \'/includes/search-tags.class.php\';
function search_tags_closure() {
$search_tags = new Search_Tags;
$search_tags->create_taxonomy();
}
add_action(\'init\', \'search_tags_closure\');
search-tags.class.php
class Search_Tags
{
const NAME = \'search_tag\';
const LABEL = \'Search Tags\';
protected function get_post_types()
{
$args = [
\'public\' => \'true\',
\'publicly_queryable\' => \'true\',
];
$post_types = get_post_types($args, \'names\');
$post_types[\'page\'] = \'page\';
unset($post_types[\'attachment\']);
return array_keys($post_types);
}
protected function is_custom_post_type($name)
{
$built_in_post_types = [
\'post\',
\'page\',
];
if (in_array($name, $built_in_post_types)) return false;
return true;
}
public function create_taxonomy()
{
$name = $this::LABEL;
$labels = [
\'name\' => $name,
\'menu_name\' => $name,
\'singular_name\' => \'Search Tag\',
\'all_items\' => "All $name",
\'edit_item\' => "Edit $name",
\'view_item\' => "View $name",
\'update_item\' => "Update $name",
\'add_new_item\' => "Add New $name",
\'new_item_name\' => "New $name",
\'search_items\' => "Find $name",
\'add_or_remove_items\' => "Add or remove $name",
];
$args = [
\'labels\' => $labels,
\'show_in_nav_menu\' => false,
];
register_taxonomy($this::NAME, $this->get_post_types(), $args);
foreach ($this->get_post_types() as $post_type) {
register_taxonomy_for_object_type($this::NAME, $post_type);
}
}
}
以上一切都很好。分类法已注册,我已向页面添加了标记。
下面是我必须按照search\\u标记分类法查询页面的代码。我临时为tax\\u查询词硬编码了一个值来测试它。我确信当我使用WP CLI列出术语和分类法时,术语和分类法是存在的。
functions.php
function testing() {
$args = [
\'post_type\' => [
\'post\',
\'page\',
\'product\',
\'distribution_centre\',
],
\'numberposts\' => -1,
\'post_status\' => \'publish\',
\'tax_query\' => [
[
\'taxonomy\' => \'search_tag\',
\'field\' => \'name\',
\'terms\' => \'Nothing\',
]
]
];
return get_posts($args);
}
var_dump(testing());