php - Remove the first 5 characters of the_title and orderby that

admin2025-06-02  0

I have a custom post type where all titles are dates (in this format: YYYY-MM-DD). I need to order them by month then day, but not at all by year. So I imagine I need a filter to 'look' 5 characters into the title and sort by that. The results I'm looking would be like this:

  • 2015-01-01
  • 2018-01-28
  • 2017-05-31
  • 2018-06-14
  • 2014-06-21

These posts have corresponding ACTUAL dates via Advanced Custom Fields datepicker so it may be easier to use that instead of the title. I've tried to figure it out both ways to no success. I'd be happy with a solution either way.

I have a custom post type where all titles are dates (in this format: YYYY-MM-DD). I need to order them by month then day, but not at all by year. So I imagine I need a filter to 'look' 5 characters into the title and sort by that. The results I'm looking would be like this:

  • 2015-01-01
  • 2018-01-28
  • 2017-05-31
  • 2018-06-14
  • 2014-06-21

These posts have corresponding ACTUAL dates via Advanced Custom Fields datepicker so it may be easier to use that instead of the title. I've tried to figure it out both ways to no success. I'd be happy with a solution either way.

Share Improve this question asked Mar 2, 2019 at 21:15 user2215732user2215732 112 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

WordPress WP_Query's orderby parameter has a lot of options but nothing as specific as what you are after.

I think you’d have to do this after retrieving posts through the WP_Query, then sort them using usort().

Your code should be something like this.

$args = array(
    'post_type' => 'z_day',
    'posts_per_page' => -1,
    'meta_query' => array(
                      array( 
                         'key' => 'day_add_almanac', 
                         'value' => 'yes' 
                       )
                    ) 
    );

// Create object
$my_posts = new WP_Query( $args );

// Sort
usort( $my_posts->posts, function( $a, $b ) {

    // Convert "2018-01-28" to "0128"
    $c = str_replace('-', '' ,substr($a->title , 5));
    $d = str_replace('-', '' ,substr($b->title , 5));

    if( $c == $d ) {
        return 0;   
    }
    // Use < or > (or swap -1 and 1 ) for reversing order
    return ( $c > $d ) ? -1 : 1;  

});

// Loop
if( $my_posts->have_posts() ) {

    while( $my_posts->have_posts() ) {

        $my_posts->the_post();

        // Show posts
        the_title();

    }

}

You may now adjust the above code to meet your requirements.
I hope this helps.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748847004a314218.html

最新回复(0)