Compare date values in Wordpress Wp_Query - wordpress

I’m running a WordPress website with around 35 000 customs posts.
Each post has a birthday value date (format DD/MM/YYYY) stored in a ACF field named birthday
Example :
$birtday_date = get_field("birthday"); //example 02/07/1955
I would like to run 2 queries in order to compare each post birthday value with the 34999 other birthday dates values in my wordpress, count and display the number of people older and younger.
Here is my code but it doesn’t work as I don’t really understand how to compare a value
Can you help me with that ?
<?php
$args = array( // args and query to look for older people that $birthday_date
'posts_per_page' => -1,
'post_type' => 'people',
'meta_key' => 'birthday',
'meta_value' => $birthday_date,
'compare' => '>',
'type' => 'DATE'
);
$query = new WP_Query($args);
$superior = $query->found_posts;
wp_reset_query();
$args2 = array( // args and query to look for younger people that $birthday_date
'posts_per_page' => -1,
'post_type' => 'people',
'meta_key' => 'birthday',
'meta_value' => $birthday_date,
'compare' => '<',
'type' => 'DATE'
);
$query2 = new WP_Query($args2);
$inferior = $query2->found_posts;
wp_reset_query();
echo $superior; // should display the number of older people but display number of people born the same day than $birthday_date
echo $inferior; // should display the number of younger people but display number of people born the same day than $birthday_date
Thanks for your help.
Regards.

You probably only need one actual query here, I'd suggest using just get_posts instead since you're not looping anything. And you can just count the difference from the total number of posts in the post type.
<?php
$birthday_date = get_field("birthday");
// Count the total number of posts in the post type and get the ones that are published. Note this shorthand only works in PHP5
$total_posts = wp_count_posts('people')->publish;
// Use this for PHP4
// $count_posts = wp_count_posts('people');
// $total_posts = $count_posts->publish;
$args = array( // args and query to look for older people that $birthday_date
'posts_per_page' => -1,
'post_type' => 'people',
'meta_query' => array(
'key' => 'birthday',
'value' => $birthday_date,
'compare' => '>',
'type' => 'DATE'
)
);
// Get the posts with the older birthdays
$older_birthdays = get_posts($args);
// Count the number of posts in the older birthdays
$num_of_older_bdays = count($older_birthdays);
// Calculate the other birthdays remaining
$num_of_younger_bdays = $total_posts - $older_birthdays;
// Display your birthday counts
echo $num_of_older_bdays;
echo $num_of_younger_bdays;

Related

Wordpess Timber - combine $context to get two post-types?

On my homepage I would like to show the most recent new items (standard Wordpress 'posts') OR events (custom post-type) in date order. I have the following bringing in each content-type, but what I get is all the events in date order; followed by all the news items in date order - what I want is News OR Events in date order, so if the newest item is an Event, then that's what comes first, followed by a News item, followed be an Event if necessary and so on. I assume there's some way to combine the context?
<?php
$context = Timber::context();
$context['home_page_content'] = new Timber\PostQuery('post_type=vopthomepage');
// below are the two I want to combine
$eventArgs = array(
'post_type' => 'mec-events',
'posts_per_page' => -1,
'orderby' => array(
'date' => 'DESC'
));
$context['mec_events'] = new Timber\PostQuery($eventArgs);
$postArgs = array(
'post_type' => 'post',
'posts_per_page'=> -1,
'category_name' => 'featured',
'orderby' => array(
'date' => 'DESC'
));
$context['featured_items'] = new Timber\PostQuery($postArgs);
Timber::render( 'index.twig', $context );
Any help greatly appreciated!
If you wanted to combine the two queries and then sort them, you could first merge the query results into a single array that you then sort with wp_list_sort().
<?php
$context = Timber::context();
$context['home_page_content'] = new Timber\PostQuery('post_type=vopthomepage');
$eventArgs = [
'post_type' => 'mec-events',
'posts_per_page' => 10,
'orderby' => [
'date' => 'DESC',
],
];
$postArgs = [
'post_type' => 'post',
'posts_per_page' => 10,
'category_name' => 'featured',
'orderby' => [
'date' => 'DESC',
],
];
$events = new Timber\PostQuery( $eventArgs );
$featured_items = new Timber\PostQuery( $postArgs );
$posts = array_merge( $events->get_posts(), $featured_items->get_posts() );
$posts = wp_list_sort( $posts, 'post_date', 'DESC' );
// Restrict to certain amount of items.
$posts = array_slice( $posts, 0, 6 );
$context['posts'] = $posts;
Timber::render( 'index.twig', $context );
You can then loop through that custom-built posts array in Twig
{% for post in posts %}
{# Display post teaser #}
{% endfor %}
What I would do is restrict the amount of posts that you fetch for each of the queries.
This works well if the amount of published posts and events are about the same over time. However, you could end with only events or posts showing up, if the newest posts are only from one type.
To work around that, you could e.g. only fetch 3 posts of each post types to make it a total of 6. You could still use wp_list_sort(), but that way you would have at least 3 of each post types displayed.
You could also try to use more than one post type for the post_type argument in WP_Query – it accepts an array of post types, but I guess that wouldn’t work if you only want to include posts from the featured category.

WP Query to compare today's day with custom field date for showing birthday's today

I am using ACF's datepicker for custom field to add birthday. THe format is January 7, 2019. I want to show artists having their birthday today. Following is my loop code but I'm stuck with how to compare today's day and month with the value stored in custom field.
<?php
$today = date("F j");
$args2 = array (
'post_type'=> array( 'artist'),
'posts_per_page' => '-1',
'meta_key' => 'artist_birth_date',
'meta_query' => array(
array(
'key' => 'artist_birth_date',
'meta-value' => $today,
'compare' => '='
)
)
);
$the_query2 = new WP_Query( $args2 );
?>

Wordpress Custom Field Query-Date Field

I have a custom field 'birthday' which displays in the format (Ymd) .
I want to query posts that have their month(m) field equal to the current month so I can congratulate people throughout the month.
I know that I will have to match the birthdays month part(substring?) to something like $date = date('m');
But am not sure how to go about building the query...Thanks in advance.Cheers
about the query should be like this
$args = array(
'meta_query' => array(
array(
'key' => 'birthdays',
'value' => '$m',
'compare' => 'IN',
),
),
);
query_posts( $args );

wordpress get_posts ordered by custom field which is a custom date

i have a custom post type for members and the birth date is saved like 01.01.2013
$args = array(
'numberposts' => -1,
'post_type' => 'mitglied',
'post_status' => 'publish',
'meta_key' => 'geburtsdatum',
'meta_value' => date("d.m.Y"),
'meta_compare' => '>',
'orderby' => 'meta_value',
'order' => 'ASC'
);
$geburtstage = get_posts ( $args );
i want a list with the birthdays of the members ordered by month and day like this
4th of january, person 10
8th of march, person 2
...
1st of december, person 3
with the code above the list is ordered by day
1st of december, person 3
4th of january, person 10
8th of march, person 2
also important is, that the ordering is not influenced by the year of birth
You have stored the date in the wrong format in your custom field. You should have used a UNIX stamp or else a format like Y-m-d, which allows to sort chronologically.
The only solution you have now is to retrieve your results without sorting them (forget 'order' => 'ASC') but also without limiting them (because your date limit is not working even if it looks like it does), create an array with all that, convert the date time as a UNIX timestamp (using strtotime) and sort by date...
But my real advice would be to refactor your site using timestamps or properly formated dates (Y-m-d). You could create a loop that goes through every post and replaces the value of your custom field with the equivalent value in UNIX, using this :
$oldvalue = get_post_meta($post_id, 'geburtsdatum', true);
update_post_meta($post_id, 'geburtsdatum', strtotime($old_value));
Please backup your database before this or at least make a test on ore or two posts, but this should solve it. Then you will be able to later use :
date("d.m.Y", $yourunixstamp)
to get formated dates.
And then, also, your previous code will just become :
$args = array(
'numberposts' => -1,
'post_type' => 'mitglied',
'post_status' => 'publish',
'meta_key' => 'geburtsdatum',
'meta_value' => time(),
'meta_compare' => '>',
'orderby' => 'meta_value',
'order' => 'ASC'
);
$geburtstage = get_posts ( $args );
I think my task is not solveable with get_posts only, so i did it in 3 steps.
First, i used get_posts to get all members
$args = array(
'numberposts' => -1,
'post_type' => 'mitglied',
);
$geburtstage = get_posts ( $args );
Then filled an array with the data. For sorting I made a timestamp with the day and month of the birthday, but the actual year.
Although with this solution it would not have been necessary, I changed the date format to yyyy-mm-dd. #barakadam explained in his answer to my question how to do this.
I use the wordpress plugin Advanced Custom Fields, so I fetch the custom fields with get_field()
$mitglieder = array( array() );
$i = 0;
foreach($geburtstage as $post){
setup_postdata( $post );
$datum = explode( "-",get_field('geburtsdatum') );
$mitglieder[$i]['orderby'] = mktime(0, 0, 0, (int)$datum[1], (int)$datum[2], date('Y'));
$mitglieder[$i]['name'] = get_field( 'name' );
$i++;
}
The last step is using array_multisort to get the intended order
foreach ($mitglieder as $key => $row) {
$dates[$key] = $row['orderby'];
}
array_multisort($dates, SORT_ASC, $mitglieder);
Thanks to #barakadam and #Christopher for participating.

Show post based on the value of another custom field

How do you display posts based on the value of one of its custom fields? My code below doesn't seem to work:
$args = array(
'post_type' => 'sample-cpt',
'meta_query ' => array(array('key'=>'cpt_display', 'value' => 1))
);
$samples = new WP_Query($args);
This still returns all posts even if the value of cpt_display is a 0. Am I missing something?
Try this..
Adding the meta_key = key as part of the args,
then include it again in the meta_query array
$args = array(
'post_type' => 'sample-cpt',
'meta_key' => 'key',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'key',
'value' => 1
)
)
);
$samples = new WP_Query($args);
http://codex.wordpress.org/Class_Reference/WP_Query
I found the answer. The value of 'meta_value' needs to be an array not a string. This is a huge deviation from the WP_Query Codex and needs to be fixed.
$args = array(
'post_type' => 'sample-cpt',
'meta_key' => 'cpt_display',
'meta_value' => array(1)
);
$samples = new WP_Query($args);
wp_reset_query();
Now it only shows posts with the custom field value of 1. Looking at the request query, it shows that by using an array, the request gets converted into using the SQL IN() to search for posts instead of '=':
...postmeta.meta_key='cpt_display' AND CAST(postmeta.meta_value AS CHAR) IN ('1'))...
Source: Display custom post type by custom field date range

Resources