Order terms by term_order

时间:2013-03-25 作者:izharbuen

Context

  • 帖子类型:资源分类法:媒体类型,术语:音频分类法:系列
    • 以下代码显示自定义分类法“系列”的唯一列表

      我想按term\\u顺序排列列表,但它不起作用。有什么建议吗?

      这个site. 目前按ID订购

          <?php
                      $post_data = array();
      
                      $my_query = new WP_Query( array( 
                              \'post_type\' => \'resource\',
                              \'posts_per_page\' => -1,
                              \'media_type\' => \'audio\'
      
                          ) 
                      );
      
                      if ( $my_query->have_posts() ) {
                          while ( $my_query->have_posts() ) {
                              $my_query->the_post();
                              $post_data[] = get_the_ID();
                          }
                      }
      
      // Start with whatever ID you want to have from Media Type
                      $audio = 16;
      
                      // Get all those post_ids for that term
                      $post_ids = get_objects_in_term( $audio, \'media_type\', array(\'post_status\' => \'publish\') );
      
                      // Then get the series terms for those post ids
                      $terms = wp_get_object_terms( $post_data, \'series\', array(\'fields\' => \'ids\', \'orderby\' => \'menu_order\' ) );
                      $result = array_values( array_unique($terms) );
      
                      ?>
      
      
                  <?php
              $a = $result;
      
              foreach ($a as $v) {
              $term = get_term( $v, \'series\' );
              $name = $term->name;
              $slug = $term->slug;
              echo \'<div class="resource-item"><a href="\'.get_term_link($slug, \'series\').\'" title="\'.$name.\'"><div class="play"></div><li>\'.$name.\'</li></a></div>\';      
              } 
      
              ?>
      

6 个回复
SO网友:Ben White

由于这是谷歌上最热门的搜索结果之一,而且上面的所有搜索结果对我来说都不太奏效,所以这条搜索结果的返回顺序似乎与它们在管理中的显示顺序相匹配。。。

 get_terms([
  \'taxonomy\'   => \'whatever_you_want\',
  \'meta_key\'   => \'order\',
  \'orderby\'    => \'meta_value_num\'
]);
为了帮助任何人,WP在termmeta表中的键顺序下存储一个值,该键顺序表示其在管理菜单中的显示位置。显然,如果您想同时查询其他meta,则需要对其进行调整。

SO网友:Jonathan Wold

而不是menu_order 尝试term_order.

根据documentation on the Codex, wp_get_object_terms 支持:

  • 名称
  • 计数
  • slug
  • 术语组
  • 术语顺序和
  • 术语id
SO网友:Dan W

term_order 不是分类法中术语的排序。它是对象(post)中术语的排序。

https://developer.wordpress.org/reference/classes/wp_term_query/__construct/ 表示:

除非$object\\u id不为空,否则“term\\u order”将与“term\\u id”相同。

对于试图为对象排序术语的人term_id, 您需要为查询提供object\\u id。

对于提出此问题的所有其他人,如果他们想订购一系列术语,请不要使用term_id. 相反,添加一个术语元值,并按其排序。

get_terms([
  \'taxonomy\'   => \'my_taxonomy\',
  \'meta_key\'   => \'order\',
  \'orderby\'    => \'meta_value_num\'
]);

SO网友:SkyRar

wp_term_query 不接受term_order 作为orderby参数之一。因此,您必须通过向函数中添加以下代码片段,将该选项强制添加到term查询变量中。php。

function wpcf_filter_terms_order( $orderby, $query_vars, $taxonomies ) {
    return $query_vars[\'orderby\'] == \'term_order\' ? \'term_order\' : $orderby;
}

add_filter( \'get_terms_orderby\', \'wpcf_filter_terms_order\', 10, 3 );
在添加以上代码段后,如果您将执行下面的操作,它将按term\\u顺序为您提供terms order。

$terms = get_terms(\'category\', array(
                    \'orderby\'  => \'term_order\',
                    \'order\'    => \'ASC\'
                ));
第二种方法是,如果您想在全球和整个wordpress中按term\\u顺序获取术语,只需在函数中添加以下片段即可。php。

function uc_get_terms_orderby($orderby, $args){
        return \'t.term_order\';
}
add_filter(\'get_terms_orderby\', \'uc_get_terms_orderby\', 10, 2);

SO网友:Cédric Dagherir - DaHive

多年后,

您可以在函数中添加此代码。php:

function wpcf_filter_terms_order( $orderby, $query_vars, $taxonomies ) {
    return $query_vars[\'orderby\'] == \'term_order\' ? \'term_order\' : $orderby;
}

add_filter( \'get_terms_orderby\', \'wpcf_filter_terms_order\', 10, 3 );
此代码强制WP在术语查询中使用term\\u order参数。

SO网友:Daniel Gross

这是一个想法,但我想在前端排序一个列表,您需要更改表“{prefix}term\\u taxonomy”,创建“term\\u order”字段。请参阅函数O\\u term\\u update\\u db():

在您的功能中。php

<?php
function O_term_update_db(){
    global $wpdb;
    global $term_db_version;
    $term_db_version = "1";

    $charset_collate = $wpdb->get_charset_collate();

    if(get_site_option( \'O_term_db_version\' ) < $term_db_version):

        require_once( ABSPATH . \'wp-admin/includes/upgrade.php\' );

        $wpdb->query( "ALTER TABLE $wpdb->prefix .\'term_taxonomy\' ADD `term_order` INT (11) NOT NULL DEFAULT 0;" );

        update_site_option( \'O_term_db_version\', $term_db_version);
    endif;
}
add_action(\'init\',\'O_term_update_db\');
?>
此函数引用函数中的数据库:
。php

<?php
function O_taxonomy_filter_by_order($taxonomy){
    global $wpdb;
    $terms = $wpdb->get_results(" 
        SELECT t.*, tt.*
        FROM ".$wpdb->prefix."term_taxonomy AS tt
        JOIN ".$wpdb->prefix."terms AS t
        ON t.term_id = tt.term_id
        WHERE tt.taxonomy = \'".$taxonomy."\'
        ORDER BY tt.term_order ASC
    ",ARRAY_A);
    return $terms;
}
?>
此函数用于通过函数中的Ajax更新表。php

<?php
if(!function_exists(\'O_updating_data_term_reorder\')){ 
    function O_updating_data_term_reorder() {

        check_ajax_referer(\'o-nonce\', \'security\');

        global $wpdb;
        $terms_ID = $_POST[\'each_term\'];

        $new_order = 0;

        foreach($terms_ID as $key => $ID):

            $term_ID = $ID[\'term\'];

            $new_order++;

            $result = $wpdb->update($wpdb->prefix.\'term_taxonomy\', array(\'term_order\' => $new_order), array(\'term_id\' => $term_ID));

            if(is_wp_error($result)) {
                echo json_encode(array(\'save\'=>false, \'message\'=> \'ERROR: \'.$result->get_error_message()));
                exit();
            }

        endforeach;

        echo json_encode(array(\'save\'=>true, \'count\'=>$new_order));

        die();
    }
    add_action( \'wp_ajax_o_update_term_reorder\', \'O_updating_data_term_reorder\' );
}
?>
可拖动ajax。js公司:

(function($) {
    "use strict";

     //jQuery Sortable is required http://api.jqueryui.com/sortable/
     //Call "wp_enqueue_script(\'jquery-ui-sortable\');" in your wp_enqueue_scripts
     $(\'.js-draggable-items > .draggable-column\').sortable({
        connectWith: \'.draggable-column\',
        items: \'.draggable-item\',
        dropOnEmpty: true,
        opacity: .75,
        handle: \'.draggable-handler\',
        placeholder: \'draggable-placeholder\',
        tolerance: \'pointer\',
        start: function(e, ui){
            ui.placeholder.css({
                \'height\': ui.item.outerHeight(),
                \'margin-bottom\': ui.item.css(\'margin-bottom\')
            });
        }
    });

    $(document).on( "click","#btn-reorder-terms", function() {
        var each_term_list = [];
        $(\'.draggable-item\').each(function(){
            each_term_list.push({
                term: $(this).attr(\'data-draggable-id\'),
            });
        });
        var data = {
            \'action\' : \'o_update_term_reorder\',
            \'each_term\' : each_term_list,
            \'security\' : actions_vars.nonce
        };
        $.ajax({
            type: \'POST\',
            dataType: \'json\',
            cache: false,
            url: actions_vars.ajaxurl,
            data: data,
            success: function(data) {
                if(data.save === true){
                    //success message here
                    alert(\'Done\');
                }else{
                    //error message here
                    alert(\'Something wrong\');
                }
            },
            error: function(errorThrown) {
               console.log(data);
            }
        });
    });

})(jQuery);
在前端列表中,尝试以下操作:

<?php
$terms = O_taxonomy_filter_by_order(\'your_taxonomy\');
?>
<button type="button" class="btn btn-primary" id="btn-reorder-terms">Save</button>

<div class="col-md-12 js-draggable-items">
    <div class="row draggable-column">
    <?php
    foreach($terms as $key => $term):
        $ID = $term[\'term_id\'];
        $name = $term[\'name\'];
        $order = $term[\'term_order\'];
        $description = $term[\'description\'];
        $link = get_category_link($ID);
        ?>
        <div class="draggable-item" data-draggable-id="<?php echo $ID;?>" data-term-order="<?php echo $order;?>">
            <div class="col-md-2 draggable-handler"><i class="si si-cursor-move"></i></div>
            <div class="col-md-10"><?php echo $name;?></div>
        </div>
        <?php
    endforeach;
    ?>
    <div>
<div>

结束