2

I am running a query which pulls out the most popular taxonomy terms (named "cause") from a custom post type (named "reasons") and I am ordering them by most popular.

However, I need to limit the terms retrieved to the ones assigned to posts submitted within the last 12 hours.

The code I currently have is as follows:

$terms = get_terms('cause', 'orderby=count&order=desc&hide_empty=0&number=6');

foreach ($terms as $term) {

  ...

}
2
  • What does "limit to the last 12 hours" mean?
    – s_ha_dum
    May 11, 2014 at 22:55
  • I only want to check for posts submitted within the last 12 hours May 11, 2014 at 23:12

1 Answer 1

0

The WordPress API has no function available to do this. You can do one of things:

  1. Use $wpdb and create a custom SQL table to retrieve terms for posts published within the last 12 hours. The only problem with this approach is that if (unlikely anytime soon) WordPress were to changes its databse scheme you may have to update the SQL statement.
  2. Use get_posts() to get posts published within the last 12 hours, loop through them and pull out their terms. This disadvantage here is that its slightly less efficient than (1).

(2) is fairly straightforward to do, so I'll leave out the details. The following is a (completely untested) attempt of (1):

function wpse144088_get_latest_terms(){

     $last_12_hours = new DateTime( '-12 hours' );
     $sql = $wpdb->prepare("
         SELECT DISTINCT t.*
         FROM {$wpdb->terms} AS t
         INNER JOIN {$wpdb->term_taxonomy} AS tt  
         ON t.term_id = tt.term_id 
         JOIN {$wpdb->term_relationships} AS tr
         ON tr.term_taxonomy_id = tt.term_taxonomy_id
         JOIN {$wpdb->posts} AS p
         ON p.ID = tr.object_id
         WHERE tt.taxonomy IN ('cause')
         AND p.post_type = 'reasons'
         AND p.post_status = 'publish'
         AND p.post_date_gmt > %s
         ORDER BY t.name ASC;",
         $last_12_hours->format( 'Y-m-d H:i:s' )
     );
     $recent_terms = $wpdb->get_results( $sql );

     return $recent_terms;
}

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.