WordPress.org

Ready to get started?Download WordPress

Forums

Sorting by custom field where custom field is an array (4 posts)

  1. symmetrium
    Member
    Posted 3 years ago #

    Hi!
    I need to sort posts on the home page by a date value contained within an array that is stored in a custom field.

    In other words, the custom field contains an array called 'data' and the value by which I would like to sort posts is contained in $data['my_date'].

    How would one go about setting up the arguments for query_posts() to achieve this?

  2. keesiemeijer
    moderator
    Posted 3 years ago #

    How did you pass the array to the custom field? did you serialize the array or do you have a custom field "data" with a "date" value?

  3. symmetrium
    Member
    Posted 3 years ago #

    Hi keesiemeijer -

    -> I stored the date in the array: $data['my_date']= "02/12/2010";

    (the array $data contains all the different pieces of information that I need to access here and there and there are a lot of them so I thought it would be more practical to store them all in one single array variable))

    -> then I create a post with
    wp_insert_post( $my_post );

    -> and then I use
    add_post_meta($myinsertedpostID, 'data', $data);

    (Unfortunately, having the date stored as a string was enough until now so that's what I did :/)

  4. keesiemeijer
    moderator
    Posted 3 years ago #

    the array $data contains all the different pieces of information that I need to access here and there and there are a lot of them so I thought it would be more practical to store them all in one single array variable

    This isn't more practical because now you can't query them individually.

    add_post_meta serializes the array anyway.

    I tried this and it pulled out the right post (ID 834):

    $data = array('my_date' => '02/12/2010', 'color' => 'blue');
       add_post_meta(834, 'data', $data);
       $query = "SELECT * FROM $wpdb->postmeta WHERE meta_key = 'data' AND meta_value LIKE '%my_date%' AND meta_value LIKE '%02/12/2010%'";
       $results = $wpdb->get_results($query);
    
       // for testing
       echo '<pre>';
       print_r($results );
       echo '</pre>';

Topic Closed

This topic has been closed to new replies.

About this Topic