Question

I have 2 custom meta one for the start date of my event and one for the end date of my event and I need to order my events according to the start date and to remove them when the end date is over.

Meta:

Start date: date_de_levenvement End date: date_de_fin

Here is my loop:

<?php query_posts( 'post_type=agenda&meta_key=date_de_fin&meta_compare=>=&meta_value=' . $todaysDate . '&orderby=meta_value&order=ASC'); ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
$date = get_field('date_de_fin');
$newDate = date("d/m/Y", strtotime($date)); ?>

Just need to change the query but I don't know how to use 2 parameters with the meta value. &orderby=meta_value needs to be something like &orderby="date_de_levenement"

Was it helpful?

Solution

I would actually use the more robust WP_Query object to accomplish this task. More specifically, you can see the section called Custom Field Parameters and see the example titled Multiple Custom Field Handling. You can create your arguments array like so:

$args = array(
        'post_type' => 'agenda',
        'meta_key' => 'date_de_levenvement',
        'meta_query' => array(
            array(
                'key' => 'date_de_fin',
                'value' => $todaysDate,
                'compare' => '>='
                )
            ),
        'orderby' => 'meta_value_num',
        'order' => 'ASC'
        );

$your_custom_query = new WP_Query($args);

// The Loop
if ( $your_custom_query->have_posts() ) {
    while ( $your_custom_query->have_posts() ) {
        $your_custom_query->the_post();
        // your code goes here
    }
} else {
    // no posts found
}
/* Restore original Post Data */
wp_reset_postdata();

Explanation

The meta_query element is an array of arrays which means you can even filter against multiple meta (custom field) properties if you wish. Notice that I included the meta_key element. This is what will allow you to sort by your start date. Whereas the key element of the meta_query element is what will filter your end date posts. (In this situation, post types named agenda will only be included if their date_de_fin is greater than or equal to "today".

[edit]

Note that the "today" date should be formatted in SQL format like so:

<?php $todaysDate = date('Y-m-d'); ?>

Hope this helps a bit. Have fun!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top