Advertisement
ikamal7

parent term count.php

Oct 19th, 2020
273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.31 KB | None | 0 0
  1. <?php
  2.  
  3. function get_term_post_count( $taxonomy = 'category', $term = '', $args = [] ) {
  4.     // Lets first validate and sanitize our parameters, on failure, just return false
  5.     if ( !$term ) {
  6.         return false;
  7.     }
  8.  
  9.     if ( $term !== 'all' ) {
  10.         if ( !is_array( $term ) ) {
  11.             $term = filter_var( $term, FILTER_VALIDATE_INT );
  12.         } else {
  13.             $term = filter_var_array( $term, FILTER_VALIDATE_INT );
  14.         }
  15.     }
  16.  
  17.     if ( $taxonomy !== 'category' ) {
  18.         $taxonomy = filter_var( $taxonomy, FILTER_SANITIZE_STRING );
  19.         if ( !taxonomy_exists( $taxonomy ) ) {
  20.             return false;
  21.         }
  22.  
  23.     }
  24.  
  25.     if ( $args ) {
  26.         if ( !is_array($args) ) {
  27.             return false;
  28.         }
  29.  
  30.     }
  31.  
  32.     // Now that we have come this far, lets continue and wrap it up
  33.     // Set our default args
  34.     $defaults = [
  35.         'posts_per_page' => 1,
  36.         'fields'         => 'ids',
  37.     ];
  38.  
  39.     if ( $term !== 'all' ) {
  40.         $defaults['tax_query'] = [
  41.             [
  42.                 'taxonomy' => $taxonomy,
  43.                 'terms'    => $term,
  44.             ],
  45.         ];
  46.     }
  47.     $combined_args = wp_parse_args( $args, $defaults );
  48.     $q             = new WP_Query( $combined_args );
  49.  
  50.     // Return the post count
  51.  
  52.     return $q->found_posts;
  53. }
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement