我在Wordpress中创建了一些自定义分类法,当我想在前端显示自定义帖子类型的类别时,它们会按字母顺序列出。
是否有函数代码。php可以帮助我列出Primary Category first, 那么其他类别呢?
在上面的示例中,类别显示为;美洲、欧洲、全球;,但我希望它们按“排序”;Global, 美洲、欧洲”;。第一个应为主要类别,然后按字母顺序列出其他类别。谢谢
我在Wordpress中创建了一些自定义分类法,当我想在前端显示自定义帖子类型的类别时,它们会按字母顺序列出。
是否有函数代码。php可以帮助我列出Primary Category first, 那么其他类别呢?
在上面的示例中,类别显示为;美洲、欧洲、全球;,但我希望它们按“排序”;Global, 美洲、欧洲”;。第一个应为主要类别,然后按字母顺序列出其他类别。谢谢
假设您使用的是Yoast SEO插件,我还没有对此进行测试,但我认为您可以这样做:(来源https://pretagteam.com/question/get-primary-category-if-more-than-one-is-selected)
/*
Checks for a yoast primary category, if it exists move the category to the first position in the $categories array.
*/
function yoast_primary_cat_as_first_cat($categories) {
// Check if yoast exists and get the primary category
if ($categories && class_exists(\'WPSEO_Primary_Term\')) {
// Show the post\'s \'Primary\' category, if this Yoast feature is available, & one is set
$wpseo_primary_term = new WPSEO_Primary_Term(\'category\', get_the_id());
$wpseo_primary_term = $wpseo_primary_term->get_primary_term();
$term = get_term($wpseo_primary_term);
// If no error is returned, get primary yoast term
$primary_cat_term_id = (!is_wp_error($term)) ? $term->term_id : null;
// Loop all categories
if ($primary_cat_term_id !== null) {
foreach($categories as $i => $category) {
/* Move the primary category to the top of the array
and leave the rest of the categories in the order they were in */
if ($category->term_id === $primary_cat_term_id) {
$out = array_splice($categories, $i, 1);
array_splice($categories, 0, 0, $out);
break;
}
}
}
}
return $categories;
}
add_filter(\'get_the_categories\', \'yoast_primary_cat_as_first_cat\');
我被告知,在阵列中使用这个:\'orderby\' => \'rand\' 将导致:随机排序的查询代价非常高昂,需要创建临时数据库表和扫描,因为它必须复制entireposts表,然后随机重新排序帖子,最后在销毁新表之前对新表进行实际查询。我被告知:在一个随机的日期之后,要求第一篇帖子要容易得多。有人能详细说明一下吗?是否有执行上述操作的数组代码行?如果您有任何与此相关的资源,我们将不胜感激。