0

I'd like to get the closest post to today's post; yes, I checked and search this topic and found the code working for me:

date_default_timezone_set("Europe/Warsaw");
setlocale(LC_ALL, en_GB);
$year = strftime('%Y');
$month = strftime('%m');
$day = strftime('%e');
//$hour = strftime('%k');
if($month < 10)
{
    $month = substr($month,1);
}
$argsi = array(
    'numberposts' => 1,
    'post_type' => 'koncerty',
    'orderby' => 'date',
    'order' => 'ASC',
    'date_query' => array(
        'after' => array(
            'year' => $year,
            'month' => $month
            ),
        'inclusive' => 'true'
        )
    );
$recent_post = wp_get_recent_posts($argsi, ARRAY_A);

the problem is, when I'm trying to inlude the day to the array

$argsi = array(
    'numberposts' => 1,
    'post_type' => 'koncerty',
    'orderby' => 'date',
    'order' => 'ASC',
    'date_query' => array(
        'after' => array(
            'year' => $year,
            'month' => $month,
            'day' => $day
            ),
        'inclusive' => 'true'
        )
    );

the code stopped working and I don't know why. I tried $day = strftime('%d') and then remove 0 in it if day < 10, but still nothing :/

2 Answers 2

0

You're looking for the get_adjacent_post function. This is a built-in wordpress function that you can use to get either the previous or next post from the current post.

To get the next post:

$next_post = get_adjacent_post( false, '', false, '' );

To get the previous post:

$prev_post = get_adjacent_post( false, '', true, '' ); 

You can also specify whether the post should be in the same taxonomy term and also set the taxonomy this is true.

get_adjacent_post( bool $in_same_term = false, array|string $excluded_terms = '', bool $previous = true, string $taxonomy =

'category' )

Parameters

$in_same_term

(bool) (Optional) Whether post should be in a same taxonomy term.

Default value: false

$excluded_terms

(array|string) (Optional) Array or comma-separated list of excluded term IDs.

Default value: ''

$previous

(bool) (Optional) Whether to retrieve previous post. Default true

Default value: true

$taxonomy

(string) (Optional) Taxonomy, if $in_same_term is true.

Default value: 'category'

0

thanks for reply, but this function wasn't great for me. however I solved this - I forgotten I sorted the posts by post published date and my all "futured" posts had published date lower than 'today' but month was OK. I changed published date add to wp_query part to check also not published posts and now it works ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.