• Resolved gcarnegie

    (@gcarnegie)


    Some of my posts have meta “gc_event_date” (Ymd format / 20240527) from ACF, others have it blank.

    I want to sort my WP_Query using post date where event date is blank, otherwise by event date.

    I figure thats too complex for $args, so planned to use usort after the query (before the loop) with a custom function.

    I’m sure no expert at this though, and as soon as un-comment pretty much ANY of the below code, my page falls over.

    Any assistance would be appreciated.

    global $dps_listing;
    $dps_listing = new WP_Query( apply_filters( 'display_posts_shortcode_args', $args, $original_atts ) );
    
    //my code from here down
    
    usort($dps_listing->posts,'comparefunction');
    
    ...
    ...
    ...
    
    function comparefunction($element1, $element2) { 
        $adate1 = date('Ymd',$element1->$post_date);
        $edate1 = get_post_meta( $element1->$ID, 'gc_event_date', true ); // Also in 'Ymd' format eg. 20240527
        echo $edate1;
        if( ! empty( $edate1)){    $adate1 = $edate1};
    
        $adate2 = date('Ymd',$element2->$post_date);     
        $edate2 = get_post_meta( $element2->$ID, 'gc_event_date', true );
        if( ! empty( $edate2)){    $adate2 = $edate2};
    
        return strcmp($adate1,$adate2); 
    }  

    • This topic was modified 7 months ago by gcarnegie.
Viewing 1 replies (of 1 total)
  • Thread Starter gcarnegie

    (@gcarnegie)

    It’s been a couple of days but figured I would add the solution I came up with in case anyone finds similar issues.

    if( ! empty( $edate1)){    $adate1 = $edate1}; // needs the semicolon INSIDE the closing bracket.
    
    $adate1 = date('Ymd',$element1->$post_date); // needs to use "strtodate()"
    // >>  $adate1 = date('Ymd',strtodate($element1->$post_date));
    
    '->$post_date'  & '->$ID' // - needs the $ taken off it
    
    //also changed strcmp to use if statement with explicit returns 0, -1, 1.

    • This reply was modified 6 months, 4 weeks ago by gcarnegie.
Viewing 1 replies (of 1 total)
  • The topic ‘Sorting WP-QUery based on complex criteria’ is closed to new replies.