首页 > 解决方案 > 在 WordPress 仪表板中制作自定义列以进行自定义分类 SORTABLE

问题描述

我正在努力找出这段代码有什么问题。我已经在 StackOverflow 上阅读并尝试了关于这个主题的每一个问题——我希望有人能发现一个小错误并解决它。

我有一个名为“books”的自定义帖子类型,带有自定义分类“book-series”。“book-series”分类有一个与之关联的“series-index-number”的自定义元值(用于按特定顺序显示系列)。

我想将“系列索引号”显示为主要分类页面上的列之一,并且还可以对其进行排序。

显示值是有效的。

按列排序不起作用。

这是完整的代码:

更新:我找到了解决方案 - 使用 pre_get_terms 添加一个操作,该操作将附加一个元类作为术语查询。下面的代码已更新以反映工作版本。

...

// display the series index numbers on the main series list page
add_filter('manage_edit-book-series_columns', 'add_series_index_column' );
add_filter('manage_book-series_custom_column', 'add_series_index_column_content', 10, 3 );
add_filter('manage_edit-book-series_sortable_columns', 'add_series_index_column_sortable' );
add_action( 'pre_get_terms', 'series_orderby' );
    
// add series index column to series page
function add_series_index_column( $columns ){
    $columns['series_index'] = 'Order Number';
    return $columns;
}
// add actual series index values to the table
function add_series_index_column_content( $content, $column_name, $term_id ){

    if( $column_name !== 'series_index' ){
        return $content;
    }

    $term_id = absint( $term_id );
    $display_index = get_term_meta( $term_id, 'series-index-number', true );

    if( !empty( $display_index ) ){
        $content .= esc_attr( $display_index );
    }

    return $content;
}
// make series index column sortable
function add_series_index_column_sortable( $sortable ){
    $sortable[ 'series_index' ] = 'series_index';
    return $sortable;
}

function series_orderby( $query ) {
  global $pagenow;

  if(!is_admin()) {
    return $term_query;
  }

  // WP_Term_Query does not define a get() or a set() method so the query_vars member must
  // be manipulated directly
  if(is_admin() && $pagenow == 'edit-tags.php' && $term_query->query_vars['taxonomy'][0] == 'book-series' && (isset($_GET['orderby']) || $_GET['orderby'] == 'series_index')) {
    // set orderby to the named clause in the meta_query
    $term_query->query_vars['orderby'] = 'order_clause';
    $term_query->query_vars['order'] = isset($_GET['order']) ? $_GET['order'] : "DESC";

    // the OR relation and the NOT EXISTS clause allow for terms without a meta_value at all
    $args = array('relation' => 'OR',
       'order_clause' => array(
        'key' => 'series-index-number',
        'type' => 'NUMERIC'
      ),
      array(
        'key' => 'series-index-number',
        'compare' => 'NOT EXISTS'
       )
    );
    $term_query->meta_query = new WP_Meta_Query( $args );
  }
  return $term_query;
}

...

标签: wordpresscustomcolumn

解决方案


我找到了答案!在这篇文章中: https ://wordpress.stackexchange.com/questions/159330/custom-taxonomy-custom-sortable-column/203834

解决方案是使用 pre_get_terms 将新的元查询附加到核心术语查询。

我已经更新了原始请求中的代码以显示实际运行的解决方案。


推荐阅读