-3

I am a WP developer with just little if none knowledge of PHP.
Yet I have to use a code snippet on a website to select posts with a date within a range.

Browsing around I found the following but I see all the results -no filtering.

// args
$args = array(
    'numberposts'   => -1,
    'post_type'     => 'contenuto',
    'meta_query' => [
            'key' => 'data_contenuto',
            'value' => ['2000-01-01', '2000-12-31'],
            'compare' => 'BETWEEN',
                ]
);



// query
$the_query = new WP_Query( $args );

?>
<?php if( $the_query->have_posts() ): ?>
    <ul>
    <?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <li>
            <p><?php the_title();?></p>
        </li>
    <?php endwhile; ?>
    </ul>
<?php endif; ?>

<?php wp_reset_query();  // Restore global post data stomped by the_post(). ?>
David Ansermot
  • 6,052
  • 8
  • 47
  • 82
  • 3
    Do you really have posts going back to the year 2000? – CBroe Oct 19 '22 at 13:29
  • Those are actually no posts but shows archive. That's why. Any hint about the code? – Davide Bellucci Oct 20 '22 at 06:13
  • And the `data_contenuto` meta field actually contains dates in that very same format, for the posts in question? Can you verify that by checking directly in the database (using phpMyAdmin or something)? – CBroe Oct 20 '22 at 06:20
  • 'data_contenuto' is an ACF field which output with Ymd format. – Davide Bellucci Oct 20 '22 at 07:07
  • And are `Ymd` and `Y-m-d` the same thing, in your opinion? – CBroe Oct 20 '22 at 07:12
  • No they are not. But I tested also with ['20000101', '20001231'], and it's not working either. I'm still getting all the posts. No filtering. – Davide Bellucci Oct 20 '22 at 07:35
  • Ah, you also appear to be missing one array "level" - https://developer.wordpress.org/reference/classes/wp_query/#custom-field-post-meta-parameters: _"(Note that meta_query expects nested arrays, even if you only have one query.)"_ `'meta_query' => [ [ ... ] ],` – CBroe Oct 20 '22 at 07:38

1 Answers1

0

CBroe is correct about the missing one array level, and I would also suggest defining the 'type' of your meta query, as with dates that could cause issues too:

$args  = array(
        'numberposts' => -1,
        'post_type'   => 'contenuto',
        'meta_query'  => [
            [
                'key'   => 'data_contenuto',
                'value' => [
                    '2000-01-01',
                    '2000-12-31'
                ],
                'compare' => 'BETWEEN'
                'type' => 'DATE',
            ]
        ]
    );

Another hint I can give you is, that after defining the $the_query variable, you could check the actual SQL code:

var_dump($the_query->request);

Sometimes that helps in my debugging process, about which part needs modification.

Mowar
  • 402
  • 4
  • 9