Skip Navigation

[Resolved] order custom posts by day number from the date custom field

This support ticket is created 5 years, 4 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 9:00 – 12:00 -
- 13:00 – 18:00 13:00 – 18:00 13:00 – 18:00 14:00 – 18:00 13:00 – 18:00 -

Supporter timezone: America/Jamaica (GMT-05:00)

Tagged: 

This topic contains 2 replies, has 2 voices.

Last updated by davidS-24 5 years, 4 months ago.

Assisted by: Shane.

Author
Posts
#1352781

I have created custom post for personalities (public figures) and custom field for the day of birth (wpcf-datum-narozeni). I have an array of post IDs of personalities born in a given month (i.e. March).

Now I am running a wp_query where I need to order these CPTs by day of birth (1-31), ignoring month/year. Date of birth (as a custom field) is saved as timestamp in a database. I cannot figure out how to order the posts by meta_value which takes only 'day' from the date custom field. Any ideas?

This is my code for wp_query:

$paged = (get_query_var('paged')) ? get_query_var('paged') : ((get_query_var('page')) ? get_query_var('page') : 1);
$args = array(
'post_type' => 'osobnost',
'post__in' => $posts_by_month_birth, //this is an array of post IDs
'posts_per_page' => 12,
'paged' => $paged,
'meta_key' => 'wpcf-datum-narozeni', //this is my custom field for date of birth
'meta_value' => date('d'), //need the day from the 'wpcf-datum-narozeni'...???
'orderby' => 'meta_value_num',
'order' => 'ASC',
'ignore_sticky_posts' => 1,
);
$query_related_posts = new WP_Query( $args );

#1352983

Shane
Supporter

Languages: English (English )

Timezone: America/Jamaica (GMT-05:00)

Hi David,

Thank you for getting in touch.

This is going to require some more complex coding. This is because we store the entire day as a timestamp. So in order to sort the items directly from the database you may need to use a custom sql query.

Or you can retrieve all the posts in an array with their meta values and then convert the timestamp to just a day only and remake the array with just the post ID and the Day and then sort that array.

I can only advise on what approach to take but I wouldn't be able to write such a custom code for you since it would be out of the scope of our support forum.

Thanks,
Shane

#1353013

Hi Shane,

Thank you for quick reply. I tried to retrieve the posts into array with post ID and the Day, then sort the array and run it through wp_query, but WordPress changes the order of the array anyway, despite not having any order parameters in the arguments.

Thank you anyway.

Regards,
David