Home > Enterprise >  How to get posts number with WP_Query based on post_name?
How to get posts number with WP_Query based on post_name?

Time:07-11

I am trying to write a code at my WordPress website to count posts with type (season) and contains (12-monkeys) at its slug [post_name column].

I tried this but it didn't work:

 $args = array(  
    'post_type'      => 'season',
    'name' => array(
          'key' => '12-monkeys',
          'compare' => 'LIKE',
        )
    );
    
    $queries = new WP_Query($args);
    
    $Seasons_in_Series = $queries->found_posts;
    echo  $Seasons_in_Series;

It was using at this template here : egybest

But it always shows a wrong number

CodePudding user response:

You can count all the posts which contain '12-monkeys' in the post name by using a custom sql query instead.

global $wpdb;

$post_count = $wpdb->get_var( $wpdb->prepare( "
   SELECT COUNT(*) 
   FROM {$wpdb->posts} 
   WHERE `post_name` 
   LIKE '%s%' 
   AND `post_type` = 'season' ", 
'-monkeys%' ) 
);
  • Related