Sort posts by custom field value
-
Hi there,
I’m using wck custom fields called “DoctorsName” to store names in my site and in it, there are metabox fields for “First names” and “last name”.
I wanted to sort the names by last name using wordpress meta queries but since wck custom fields is an array and meta_key doesn’t accept an array, I can’t find a way to make it work.
my code is this:
<?php $q=array( 'post_type' => 'doctors', 'order' => 'ASC', 'meta_key' => 'DoctorsName', 'orderby'=> 'meta_value', 'posts_per_page' => '10', ); $my_query = new WP_Query($q); if( $my_query->have_posts() ) : while ($my_query->have_posts()) : $my_query->the_post(); ?>
I was hoping that ‘meta_key’ =>’DoctorsName[“last-name”]’ would work but got no luck.
I would really appreciate if someone can help me out.
thanks,
https://wordpress.org/plugins/wck-custom-fields-and-custom-post-types-creator/
-
Hi,
To achieve what you want you have to use the following filter:apply_filters( ‘wck_cfc_unserialize_fields_’.$your_meta_name, false )
and you can use it like this in functions.php of your theme or a plugin:
add_filter( ‘wck_cfc_unserialize_fields_your_meta_name’, ‘wck_change_unserialize_arg’ );
function wck_change_unserialize_arg( $bool ){
return true;
}When used like this it enables for that metabox the unserialize_fields option. When enabled, besides the serialized array that is normally saved we save each individual field in it’s own meta, regardless if it’s a repeater metabox or single. The meta key will have this form: $meta_name_arg . ‘_’ . $field_slug .’_’. $n where $n starts at 1 and represents the number of the entry in the repeater. For a single metabox it will be 1.
Hope this helps.
anyone?
I had no luck with the piece of code.
They should I’ve an example.Hi drixe,
Check out the documentation page on this: http://www.cozmoslabs.com/docs/wordpress-creation-kit-documentation/how-to/store-custom-field-meta-unserialized-fields/
If you still have problems with it please tell me your meta_name (in the metabox settings) + the slugs of each field and I’ll try to give you a piece of code for this.
Also, please note, for this to work on existing records in the database, you’ll need to re-save each custom field.
Hi,
Thanks for answering.
I had a syntax problem in my custom field name ! Very sorry.
It works great.
- The topic ‘Sort posts by custom field value’ is closed to new replies.