显示自定义帖子类型的分类

时间:2019-02-25 作者:t.cvmk

我有一个自定义的帖子类型Products 使用自定义分类法product-year product-catproduct-country

我想创建如下表,但我不确定如何填充代码。

提前谢谢你

enter image description here

1 个回复
SO网友:Qaisar Feroz

这里有一个快速的解决方案,可以引导您达到预期的结果。

$years = get_terms( array(
        \'taxonomy\' => \'product-year\',
        \'hide_empty\' => true,
    ) );

    $cats = get_terms( array(
        \'taxonomy\' => \'product-cat\',
        \'hide_empty\' => true,
    ) );

if ( ! empty( $years ) && ! is_wp_error( $years ) ){
    foreach ( $years as $year ) {
        echo \'<strong>\'.$year->name.\'</strong>\';
        if ( ! empty( $cats ) && ! is_wp_error( $cats ) ){
            foreach ( $cats as $cat ) {
                echo \'<strong>\'.$cat->name.\'</strong>\';
                $args = array(
                            \'post_type\' => \'Products\',
                            \'tax_query\' => array(
                                \'relation\' => \'AND\',
                                array(
                                    \'taxonomy\' => \'product-year\',
                                    \'field\'    => \'term_id\',
                                    \'terms\'    => array( $year->term_id ),
                                    ),
                                array(
                                    \'taxonomy\' => \'product-cat\',
                                    \'field\'    => \'term_id\',
                                    \'terms\'    => array( $cat->term_id ),
                                ),
                            ),
                        );
                $query = new WP_Query( $args );
                if ( $query->have_posts() ) {
                    echo \'<table>\';
                    while ( $query->have_posts() ) {
                        $query->the_post();

                        $countries = get_the_terms( get_the_ID(), \'product-country\' );

                        if ( $countries && ! is_wp_error( $countries ) ) : 

                              $countries_links = array();

                              foreach ( $countries as $country ) {
                                  $countries_links[] = $country->name;
                               }

                              $countries_names = join( ", ", $countries_links );
                        }
                        echo \'<tr><td>\' . get_the_title( ) . \'</td>\'.\'<td>\' . $countries_names . \'</td></tr>\'  ;
                    }
                    echo \'</table>\';

                    // Restore original Post Data
                    wp_reset_postdata();
                }
            }
        }
    }
}
请注意任何拼写错误(如果有)。

相关推荐