15

wp_list_categories()用来获取所有类别的列表并生成导航栏。除了字母顺序之外,有没有办法以特定顺序对这些类别进行排序。

例如:Connect、News & Views、Q&A、Hello Startup、Startup 101...

4

7 回答 7

15

大多数主题不使用任何类别的描述。我所做的简单解决方法是在描述中使用数字。这里的顶部帖子目前有一些来自这里的 jQuery hack,它是不需要的。

我想您也可以添加自定义订单字段。

只是

$categories = get_categories( array(
    'orderby' => 'description',
    'order'   => 'ASC'
) );
于 2017-02-09T01:56:56.137 回答
5

技术方法

wordpress核心的问题是表格wp_terms没有term_order列。这意味着,标准 wordpress 不支持自定义术语顺序。如果您查看此WP 数据库结构,您可以找到该表wp_term_relationships。该表负责帖子和分类(您的类别)之间的关系,并且该表有一term_order列。

现在,使用简单的 SQL 语句ALTER TABLE wp_terms ADD term_order INT(11) NOT NULL DEFAULT 0(不要忘记$wpdb->wp_terms变量),您可以向表中添加一列,该列负责您的自定义类别顺序。wp_term_relationships然后您可以将您的自定义类别顺序放在和的这两列中wp_terms。一切都完成后,您可以连接到过滤器get_terms_args并将其更改orderbyterm_order.

这里列出了技术方法的所有相关链接:

插件可以为您完成工作

检查我的插件来解决这个问题:WordPress Real Categories ManagementWP RCM在 wp 术语表上创建一个额外的字段 term_order。它还带来了许多其他有用的功能,您可以在下面的屏幕截图中看到。它允许您以一种很好的方式组织您的 wordpress 类别。它易于使用,只需拖放您的类别并将其移动到特定顺序即可。该插件适用于所有自定义帖子类型

拖放类别顺序

从产品描述中我可以引用。如果您想尝试插件,插件页面上还有一个演示。

有很多免费插件

这可以通过 wordpress.org 插件存储库中提供的许多免费插件来解决。只需在您的 Wordpress 仪表板 > 插件 > 安装中搜索“类别顺序”。

于 2016-11-03T18:42:29.780 回答
4

这是内置的wordpress_wp_list_categories

wp_list_categories('orderby=name');

我认为这会帮助你

于 2011-04-26T05:38:00.097 回答
0

使用类别顺序和分类术语订购免费插件

于 2021-01-08T21:48:12.030 回答
0

我没有找到任何东西,所以我构建了自己的方法。我在插件的抽象类中将其抽象出来,因此有额外的代码,但您可以提取方法。

主要看方法是format_hierarchy()

// The parent class
abstract class Taxonomy {
    protected bool $_terms_loaded;
    
    protected array $terms;
    protected array $formatted_terms;
    
    public function __get( $property ) {
        if ( $property === 'formatted_terms' ) {
            if ( !isset( $this->formatted_terms ) ) $this->format_hierarchy();
            return $this->formatted_terms;
        }
        
        if ( substr( $property, 0, 1 ) === '_' ) die( 'Cannot get private properties' );

        if ( property_exists( $this, $property ) )
            return $this->$property;
    }

    /**
     * Formats the taxonomy's terms into a hierarchy of term_blocks and saves the value as a property to the class
     * 
     * @return              array       an array of `[term_taxonomy_id:number] => term_block` like:
     *                                      array(
     *                                          array( // parent $term_block
     *                                              'term' => WP_Term,
     *                                              'children' => array( $term_blocks… )
     *                                          ),
     *                                          …$term_blocks…
     *                                      )
     */
    public function format_hierarchy():array {
        if ( !$this->_load_terms() ) return [];

        // Holds a reference to every category, parents and children
        $term_blocks = [];

        // Holds a reference to every top most level category
        $parents = [];

        foreach ( $this->terms as $term ) {
            // Add itself to the list of all categories
            $term_block = [
                'children' => [],
                'term' => $term
            ];
            
            // Add itself to the array of all categories
            if ( !isset( $term_blocks[ $term->term_taxonomy_id ] ) )
                $term_blocks[ $term->term_taxonomy_id ] =& $term_block;
            
            // If it's a child category…
            if ( $term->parent !== 0 ) {
                // If the parent hasn't been created yet, create it
                if ( !isset( $term_blocks[ $term->parent ] ) )
                    $term_blocks[ $term->parent ] = [
                        'children' => [],
                        'term' => null
                    ];
                    
                $term_blocks[ $term->parent ][ 'children' ][] =& $term_block;
            } else
                // Otherwise it's a parent
                $parents[ $term->term_taxonomy_id ] =& $term_blocks[ $term->term_taxonomy_id ];

            // set the term block's WP_Term property
            $term_blocks[ $term->term_taxonomy_id ][ 'term' ] =& $term;
            // This is needed so that the loop doesn't readd the same reference over and over again
            unset( $term ); unset( $term_block );
        }
        
        return $this->formatted_terms = $parents;
    }

    /**
     * Given a WP_Term property value, and a property key, recursively searches through all of the terms for it
     * 
     * @property    $term_val       mixed       The property value to find
     * @property    $prop           string      The property key for the value
     * @property    $with_parent    ?boolean    Whether to return the top level parent as well
     * @property    $term_blocks    ?array      Array of term blocks
     * @return                      array       If $with_parent is true, returns an [ $found_term_block, $top_level_parent ]
     *                                          Otherwise returns only the found term block
     */
    public function find_term_by(
        $term_val,
        string $prop,
        bool $with_parent = false,
        $term_blocks = null
    ):?array {
        if ( is_null( $term_blocks ) ) $term_blocks = $this->formatted_terms;
        foreach ( $term_blocks as $term_block ) {
            if ( $term_block[ 'term' ]->{$prop} === $term_val ) return $term_block;
            if ( count( $term_block[ 'children' ] ) &&
                ( $found = $this->find_term_by( $term_val, $prop, false, $term_block[ 'children' ] ) )
            ) return $with_parent ? [ $found, $term_block ] : $found;
        }
        return null;
    }

    /**
     * Loads the taxonomy terms once from the DB
     */
    protected function _load_terms():bool {
        if ( isset( $this->_terms_loaded ) ) return $this->_terms_loaded;
        
        $this->terms = get_terms(
            array(static::$taxonomy),
            array(
                    'hide_empty'    => false,
                )
        );

        if ( !$this->terms ) {
            ClassErrorHandler::handle_exception(
                new \WP_Error( 500, 'Failed to load category terms: \'' . static::$taxonomy . '\'' )
            );
        }

        return $this->_terms_loaded = !!$this->terms;
    }
}

// The Implementation
class TaxonomyProductService extends Taxonomy {
    public static string $taxonomy;
    public static string $slug;

    /**
     * To be called upon taxonomy registration long before any instance is required
     */
    public static function define_taxonomy( string $slug, string $taxonomy ) {
        static::$slug = $slug;
        static::$taxonomy = $taxonomy;
    }
}

注册自定义分类后,我立即调用 TaxonomyProductService::define_taxonomy( 'url-slug', 'product-service' );

最后是如何使用的

$tax = new TaxonomyProductService();
$terms = $tax->formatted_terms;
// search for a term whose slug === `my-term`, and return the parent category
list( $current_term, $parent_term ) = $tax->find_term_by( 'my-term', 'slug', true );
于 2021-01-29T13:36:23.437 回答
0

我这样做生成了几个术语列表。我以后按我自己的命令叫它。我是 PHP 初学者。

首先,我将每个类别术语的 ID 存储在不同的变量中:

$terms = get_terms('my_taxonomy', 'hide_empty=0');
        foreach ( $terms as $term ) {
           ${$term->slug} = get_term_by('slug', $term->slug, 'product_cat');
           ${$term->slug.'_array'} = (array)${$term->slug};
           ${$term->slug.'_array_id'} =${$term->slug.'_array'}['term_id'];
      };

然后,我为每个wp_list_categories()排除创建几个 args,使用这个变量我想要的术语:

      $args = array(
        'taxonomy'     => 'my_taxonomy',
        'orderby'      => 'name',
        'show_count'   => true,
        'pad_counts'   => false,
        'hierarchical' => true,
        'title_li'     => '',
        'hide_empty'   => 0,
        'show_option_all' => 'Show all',
        'exclude'    => array( $term1_array_id, $term2_array_id )
      );

      $args_1 = array(
        'taxonomy'     => 'my_taxonomy',
        'orderby'      => 'name',
        'show_count'   => true,
        'pad_counts'   => false,
        'hierarchical' => true,
        'title_li'     => '',
        'hide_empty'   => 0,
        'exclude'    => array( $term3_array_id, $term4_array_id, $term1_array_id )
      );

      $args_2 = array(
        'taxonomy'     => 'my_taxonomy',
        'orderby'      => 'name',
        'show_count'   => true,
        'pad_counts'   => false,
        'hierarchical' => true,
        'title_li'     => '',
        'hide_empty'   => 0,
        'exclude'    => array( $term1_array_id, $term4_array_id, $term5_array_id )
      );

最后,我可以分别调用每个术语列表:

<ul>
    <?php wp_list_categories( $args ); ?>
    <?php wp_list_categories( $args_1 ); ?>
    <?php wp_list_categories( $args_2 ); ?>
</ul>
于 2016-08-24T12:49:31.570 回答
-1

为了将来的访问者的利益,这是解决此问题的简单方法:

现在有许多插件允许您在 WordPress 中订购类别或其他自定义分类法。您可以在 WordPress 插件目录的“类别顺序”标签页中看到其中的一些。我可以亲自确认Custom Taxonomy Order NE插件可以完成这项工作。

于 2015-03-11T15:56:13.600 回答