WordPress -创建一个自定义文章类型的自定义admin列(该列是一个分类)

qvsjd97n  于 2023-08-03  发布在  WordPress
关注(0)|答案(1)|浏览(164)

我创建了一个名为property的自定义帖子类型,这个CPT有一个名为property_type的分类法。在admin部分,我创建了一个自定义列,以显示CTP列表中的property_type分类,代码如下:

add_filter('manage_property_posts_columns', function($columns){
    return [
        'cb' => $columns['cb'],
        'title' => $columns['title'],
        'type' => 'Type',
        'date' => $columns['date']
    ];
});

字符串
且这

add_filter('manage_property_posts_custom_column', function($column, $postId){
    if($column ==='type'){
        $typePost = wp_get_post_terms($postId,['property_type']);
        echo $typePost[0]->name;
    }
}, 10, 2);


那很好现在,我想使这个列可排序。
在我的研究中,我发现这可以使列标题可排序

function register_sortable_columns( $columns ) {
    $columns['type'] = 'type';
    return $columns;
}
add_filter( 'manage_edit-property_sortable_columns', 'register_sortable_columns' );


这是为了管理排序:

add_action( 'pre_get_posts', 'my_slice_orderby' );
function my_slice_orderby( $query ) {
    if( ! is_admin() )
        return;
    $orderby = $query->get( 'orderby');
    if( 'type' == $orderby ) {
        $query->set('meta_key','type');
        $query->set('orderby','meta_value');
    }
}


但当我点击排序时,我有一个空白列表。有什么想法吗?谢谢

0wi1tuuw

0wi1tuuw1#

找到解决办法了。对于那些感兴趣的人:

function register_sortable_columns( $columns ) {
    $columns['type'] = 'type';
    return $columns;
}
add_filter( 'manage_edit- property_sortable_columns','register_sortable_columns' );

// Custom sorting for the "type" column
add_action( 'pre_get_posts', 'my_property_type_orderby' );
function my_property_type_orderby( $query ) {
    if ( ! is_admin() )
        return;

    $orderby = $query->get( 'orderby' );
    if ( 'type' == $orderby ) {
        $query->set( 'orderby', 'taxonomy__field' );
    
        // Check if the current order is ascending or descending and reverse it
        $order = strtoupper( $query->get( 'order' ) );
        if ( $order === 'ASC' ) {
            $query->set( 'order', 'DESC' );
        } else {
            $query->set( 'order', 'ASC' );
        }
    }
}

// Handle custom sorting
add_filter( 'posts_clauses', 'my_custom_tax_orderby', 10, 2 );
function my_custom_tax_orderby( $clauses, $query ) {
    global $wpdb;
    if ( isset( $query->query['orderby'] ) && 'taxonomy__field' === $query->query['orderby'] ) {
        $clauses['join'] .= "
            LEFT JOIN $wpdb->term_relationships AS tr ON ($wpdb->posts.ID = tr.object_id)
            LEFT JOIN $wpdb->term_taxonomy AS tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
            LEFT JOIN $wpdb->terms AS t ON (tt.term_id = t.term_id)
    ";
        $clauses['where'] .= " AND (taxonomy = 'property_type' AND tt.taxonomy = 'property_type')";
           $clauses['groupby'] = "($wpdb->posts.ID)";
        $clauses['orderby'] = "t.name " . $query->get( 'order' ); // Use the order from the query
    }
    return $clauses;

字符串
}

相关问题