• I would like to order my posts by a so called custom field. Or meta_key in other word. Meta key name is “rating”. It has a numeric value of 1..5, but it is set only for about 50% of the posts, which belongs to a given cathegory, this meta for the remaining posts will not be set.
    I found out that the value of this meta key is actually an array with only 1 element, eg. [2]. So when I would like to echo the values for each posts – only for checking them and fiddling with the value type – I had to use this code in the main Loop:

    echo get_post_meta(get_the_ID(),"rating")[0];

    Notice the indexing at the end.

    Now I have found a solution for rodering posts by the so called pre_get_posts hook:

    function my_pre_get_posts( $query ) {
    	if( is_admin() ) {
             return $query;
    	}
       if ( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'event' ) {
       $query->set('orderby', 'meta_value_num');
       $query->set('meta_key', 'rating');
       $query->set('order', 'DESC');
    }
    
     return $query;
    
    }
    
    add_action('pre_get_posts', 'my_pre_get_posts');

    I set up the meta key and the values with this Ruby code:

    server = XMLRPC::Client.new("www.example.com", "/xmlrpc.php", 80);
    server.http_header_extra = {'accept-encoding' => 'identity'};
    all_posts=server.call("wp.getPosts", 0, "username", "password",{"post_type" => "post", "post_status" => "published", "number" => "10000", "offset" => "0"}) rescue [];
    selected_posts=all_posts.select{|z| z.dig("custom_fields").find{|z| z.dig("key")=="rating"}==nil}
    
    selected_posts.each{|p|
    
      begin
        puts p["link"];
        print p["post_title"]+": ";
        rating=STDIN.readline.chomp;
      end while rating !~ /^[12345]$/ && rating!="";
      if rating !=""
        server.call("wp.editPost", 0, "username", "password",p["post_id"],{"custom_fields"=>[{"key"=>"rating","value"=>rating}]});
      end
      puts "-"*60;
      puts;
    }

    I have no clue why the value are stored as an array of 1 element.

    Now how can I mark that I would like to use the first element of the meta_key for the ordering? Is there something like meta_index?

  • The topic ‘How to order posts by a meta_key with pre_get_posts hook when value is array?’ is closed to new replies.