programing

WordPress에서 카테고리를 정렬하는 방법

iphone6s 2023. 4. 2. 10:05
반응형

WordPress에서 카테고리를 정렬하는 방법

용 i i i i를 쓴다.wp_list_categories()모든 카테고리의 목록을 가져오고 탐색 막대를 생성합니다.이러한 카테고리를 알파벳 순서 이외의 특정 순서로 정렬할 수 있는 방법이 있습니까?

예: Connect, News & Views, Q&A, Hello Startup, Startup 101...

대부분의 테마는 카테고리에 대한 설명을 사용하지 않습니다.간단한 회피책은 설명에 숫자를 사용하는 것이었습니다.여기 맨 위 게시물에는 현재 여기에서 jQuery 해킹이 몇 개 있습니다. 불필요합니다.

커스텀 오더 필드도 추가할 수 있을 것 같습니다.

그저.

$categories = get_categories( array(
    'orderby' => 'description',
    'order'   => 'ASC'
) );

기술적 접근법

이 「」라고 하는 입니다.wp_termsterm_order기둥.즉, 표준 워드프레스는 사용자 정의 용어 순서를 지원하지 않습니다.이 WP 데이터베이스 구조를 보면 표를 찾을 수 있습니다.wp_term_relationships, 이 에는 '자신의 카테고리'가 이 테이블에는term_order★★★★★★ 。

으로 단순한 스테이트먼트 "SQL"을 ALTER TABLE wp_terms ADD term_order INT(11) NOT NULL DEFAULT 0 )$wpdb->wp_termsvariable)할 수 이순서를 합니다).이 컬럼은 커스텀카테고리 순서를 담당합니다. 이 두 수 있습니다.wp_term_relationships ★★★★★★★★★★★★★★★★★」wp_terms에 접속할 수 get_terms_args 쓰세요.orderby로로 합니다.term_order.

다음은 기술적인 접근과 관련된 모든 링크 목록입니다.

  • wp 데이터베이스 구조에 대한 https://codex.wordpress.org/Database_Description
  • https://codex.wordpress.org/Class_Reference/wpdb (용)$wpdb->wp_terms
  • WP 필터의 경우 https://developer.wordpress.org/reference/hooks/get_terms_args/

플러그인으로 작업을 수행할 수 있습니다.

이 문제를 해결하려면 내 플러그인 확인:WordPress Real Categories Management.WP RCM은 wp 용어 테이블에 추가 필드 term_order를 작성합니다.또한 아래 스크린샷에서 볼 수 있듯이 많은 유용한 기능을 제공합니다.워드프레스 카테고리를 보기 좋게 정리할 수 있습니다.카테고리를 드래그 드롭하여 특정 순서로 이동하기만 하면 사용하기 쉽습니다.플러그인은 모든 사용자 지정 게시 유형에서 작동합니다.

드래그 앤 드롭 카테고리 순서

상품 설명에서 인용할 수 있습니다.플러그인을 시험해보고 싶다면 플러그인 페이지에도 데모가 있습니다.

무료 플러그인이 많이 있습니다.

이 문제는 wordpress.org 플러그인 저장소 내에서 사용할 수 있는 많은 무료 플러그인을 통해 해결할 수 있습니다.Wordpress Dashboard > Plugins > Install에서 "카테고리 순서"를 검색하기만 하면 됩니다.

이것은 내장되어 있습니다.wordpress_wp_list_categories

wp_list_categories('orderby=name');

그게 도움이 될 것 같아

몇 개의 용어 목록을 생성하며 작업을 수행했습니다.나중에 제 명령으로 전화할게요.저는 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 = 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>

카테고리 순서 및 택사노미 용어 순서 무료 플러그인 사용

나는 아무것도 찾지 못했기 때문에 나만의 방법을 만들었다.플러그인의 추상 클래스에서 추출했기 때문에 추가 코드를 사용할 수 있지만 메서드는 풀 수 있습니다.

주목해야 할 주요 방법은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;
    }
}

커스텀 분류법을 등록한 직후에 Taxonomy Product Service::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 );

향후 방문자의 편의를 위해, 이 문제에 대한 간단한 해결책을 다음에 제시하겠습니다.

이제 WordPress에서 카테고리 또는 기타 사용자 지정 분류법을 정렬할 수 있는 플러그인이 많이 있습니다.WordPress 플러그인 디렉토리의 "카테고리 순서" 태그 페이지에서 이러한 태그 중 일부를 볼 수 있습니다.Custom Taxonomy Order NE 플러그인이 작업을 수행하는 을 개인적으로 확인할 수 있습니다.

언급URL : https://stackoverflow.com/questions/517940/how-to-order-categories-in-wordpress

반응형