wp设置后台自定义列可筛选

Published
2022-10-21
浏览次数 :  27

<?php
function my_manage_MY_POST_TYPE_columns( $columns )
{
    // save date to the variable
    $date = $columns['date'];
    // unset the 'date' column
    unset( $columns['date'] ); 
    // unset any column when necessary
    // unset( $columns['comments'] );

    // add your column as new array element and give it table header text
    $columns['MY_CUSTOM_COLUMN'] = __('Custom Column Header Text');

    $columns['date'] = $date; // set the 'date' column again, after the custom column

    return $columns;
}
?>
<?php
function my_set_sortable_columns( $columns )
{
    $columns['MY_CUSTOM_COLUMN'] = 'MY_CUSTOM_COLUMN';
    return $columns;
}
?>
<?php
function my_populate_custom_columns( $column, $post_id )
{
    switch ( $column ) {
        case 'MY_CUSTOM_COLUMN':
            echo get_post_meta($post_id, 'MY_META_KEY', true);
            break;
        case 'MAYBE_ANOTHER_CUSTOM_COLUMN':
            // additional code
            break;
    }
}
?>
<?php
function my_sort_custom_column_query( $query )
{
    $orderby = $query->get( 'orderby' );

    if ( 'MY_CUSTOM_COLUMN' == $orderby ) {

        $meta_query = array(
            'relation' => 'OR',
            array(
                'key' => 'MY_META_KEY',
                'compare' => 'NOT EXISTS', // see note above
            ),
            array(
                'key' => 'MY_META_KEY',
            ),
        );

        $query->set( 'meta_query', $meta_query );
        $query->set( 'orderby', 'meta_value' );
    }
}
?>

And now let’s apply filters and actions. Check if you are not on the front-end, on the right page and the right post type is chosen:

<?php
global $pagenow;

if ( is_admin() && 'edit.php' == $pagenow && 'MY_POST_TYPE' == $_GET['post_type'] ) {

    // manage colunms
    add_filter( 'manage_MY_POST_TYPE_posts_columns', 'my_manage_MY_POST_TYPE_columns' );

    // make columns sortable
    add_filter( 'manage_edit-MY_POST_TYPE_sortable_columns', 'my_set_sortable_columns' );

    // populate column cells
    add_action( 'manage_MY_POST_TYPE_posts_custom_column', 'my_populate_custom_columns', 10, 2 );

    // set query to sort
    add_action( 'pre_get_posts', 'my_sort_custom_column_query' );
}

?>

Top