显示带有短码的自定义分类中的随机术语列表

时间:2021-11-13 作者:Peterx20

我试图从自定义分类法中输出一个术语列表。我几乎可以肯定我以前使用过这个代码段,但不知为什么WP会抛出错误:

shuffle()期望参数1为数组

/* Show Custom Taxonomy Terms */

function these_rand_tax1() {
$max = 8; //number of categories to display
$taxonomy = \'baumaschinen_cat\';
$terms = get_terms(\'taxonomy=\'.$taxonomy.\'&orderby=name&order=ASC&hide_empty=0\');


// Random order
shuffle($terms);


// Get first $max items
$terms = array_slice($terms, 0, $max);


// Sort by name
usort($terms, function($a, $b){
  return strcasecmp($a->name, $b->name);
});


// Echo random terms sorted alphabetically
if ($terms) {
  foreach($terms as $term) {
    echo \'<p><a href="\' .get_term_link( $term, $taxonomy ) . \'" title="\' .  sprintf( __( "View all posts in %s" ), $term->name ) . \'" \' . \'>\' . $term->name.\'</a></p> \';
  }
}
}


add_shortcode(\'random_taxonomies\',\'these_rand_tax1\');
add_filter(\'widget_text\', \'do_shortcode\');
如何从自定义分类术语中获得随机列表?

1 个回复
SO网友:BlueSuiter

Try this code:

function these_rand_tax1()
{
    $max = 8; //number of categories to display
    $taxonomy = \'baumaschinen_cat\';
    $terms = get_terms(\'taxonomy=\' . $taxonomy . \'&orderby=name&order=ASC&hide_empty=0\');
    $terms = (array)$terms;

    // Random order
    shuffle($terms);


    // Get first $max items
    $terms = array_slice($terms, 0, $max);


    // Sort by name
    usort($terms, function ($a, $b)
    {
        return strcasecmp($a->name, $b->name);
    });


    // Echo random terms sorted alphabetically
    if ($terms)
    {
        foreach ($terms as $term)
        {
            echo \'<p><a href="\' . get_term_link($term[\'slug\'], $taxonomy) . \'" title="\' .  sprintf(__(" View all posts in %s"), $term[\'name\']) . \'" \' . \'>\' . $term[\'name\'] . \'</a></p> \';
        }
    }
}

相关推荐

WP_DROPDOWN_CATEGORIES和自定义分类+自定义帖子类型

我已经创建了名为“的自定义帖子类型”;案例研究;(使用slug案例研究),支持自定义分类法,称为;主题;。我正在努力实现什么?简单的下拉列表,在选项选择上重定向到特定的分类术语页面。代码:<form id="category-select" class="category-select" action="<?php bloginfo(\'url\'); ?>" method="get&quo