Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

php - Wordpress sortable custom admin columns

I've added multiple custom columns to my WP admin panel:

public function admin_column_content($column_name, $post_ID) {
        global $post;
        $progress = (new Question)->get_questions_progress();
        if ($column_name == 'level_1') {
            echo $progress['level_1']['progress'];
        }
        if ($column_name == 'level_2') {
            echo $progress['level_2']['percentage'];
        }
        if ($column_name == 'level_3') {
            echo $progress['level_3']['percentage'];
        }
        if ($column_name == 'address') {
            echo get_field('street') . ' ' . get_field('house_number') . ', ' . get_field('city');
        }
    }

As you can see, the first thee options are not based on a (custom) field from that page, but it's a number generated by multiple numbers in the database.

The problem is that I want to make these columns also sortable:

public function set_sortable_columns( $columns ) {
        $columns['address'] = 'address';
        $columns['level_1'] = 'level_1';

        return $columns;
    }

    public function school_custom_orderby( $query ) {
        if( ! is_admin() )
            return;

        $orderby = $query->get('orderby');
        $progress = (new Question)->get_questions_progress();

        if('address' == $orderby) {
            $query->set('meta_key','street');
            $query->set('orderby','meta_value');
        } elseif ('level_1' == $orderby) {
            $query->set('meta_key', '');
            $query->set('orderby','meta_value_num');
        }  
    }

The address column is working because I can set the meta_key value to street, which is a ACF field in that custom post type. But how to make level_1, level_2 and level_3 sortable? They don't have a dedicated field in the CPT.

Thanks in advance!

Best wishes Joeri

question from:https://stackoverflow.com/questions/65881935/wordpress-sortable-custom-admin-columns

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...