WordPress: How to Sort Post list custom column - multi deep level custom meta?

346 Views Asked by At

meta key is test, however it's an object.
Example:

$data = get_post_meta($post_id, "test", true);
echo $data["a"];
echo $data["b"];
echo $data["c"];

Question:

  • How to sort data by custom meta (in object form) in WordPress post list.
  • I'd like to sort A, B and C columns.

ref

Ref: wp_meta_query


<!-- Post Editor | custom field in MetaBox -->
<input name="test[a]" />
<input name="test[b]" />
<input name="test[c]" />
<button type="submit">Submit</button>

add_filter("manage_customPost_posts_columns", function($col) {
    $col["a"] = "A";
    $col["b"] = "B";
    $col["c"] = "C";
    return $col;
});

//________________________________________________________

add_filter("manage_edit-customPost_sortable_columns", function($col) {
    $col["a"] = "a";
    $col["b"] = "b";
    $col["b"] = "c";
    return $col;
});

//________________________________________________________

add_action("pre_get_posts", function($query) {
    $orderby = $query->get("orderby");

        // ▼▼▼ Issue start from here ▼▼▼
        $meta_query = array(
            "key" => "test[".$orderby."]",
        );
        $query->set("meta_query", $meta_query);
        $query->set("orderby", "value");
        // ▲▲▲ Issue end from here ▲▲▲

});
1

There are 1 best solutions below

0
On

So pre_get_posts filters a WP_Query object which means anything you could do via query_posts() you can do via $query->set() and $query->get(). In particular we can make use of the meta_query attribute (see Codex):

//Get original meta query
$meta_query = $query->get('meta_query');

//Add our meta query to the original meta queries
$meta_query[] = array(
    'key'=>'featured',
    'value'=>'yes',
    'compare'=>'!=',
);
$query->set('meta_query',$meta_query);