• Resolved elena18

    (@elena18)


    I need to show a counter within my single page post (I use it as a shortcode).

    I have a custom post type (slug = ‘portfolio’) that has different categories.

    When I am in the single post, I want to display a counter such as “n/tot” where

    n= the post number (first post within the category = 1; second post within the category = 2; etc)
    tot = total number of posts within that category

    I found the way to show the total number of posts, but not within a category

    add_shortcode( 'tot_posts', 'number_factsheets' );
    function number_factsheets () {
    
        $total = wp_count_posts('portfolio')->publish;
        $output = '<div class="count">';
        $output .= $total;
        $output .='</div>';
      return $output; 
      
    }
    

    Is it possible to obtain the data above when I am in single page post? And how?

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator bcworkz

    (@bcworkz)

    The simplest is to use WP_Query to query for the posts you want a count of. Specify the “posts_per_page” arg as a low number since you don’t really need post data, just the count. Use other args like “cat” or “tax_query” to limit the query to what posts you want counted. The query object’s $found_posts property will contain the total count of all posts matching the query’s args.

    Thread Starter elena18

    (@elena18)

    Thanks @bcworkz. I went on digging into the problem and I am almost there. However I still don’t understand hot to retrieve the category number when I know the post_ID.

    So here’s my working code

    Here is my code that output n/tot. Unfortunately the “tot” corresponds to all posts (disregarding their category). Since the posts have a single category, I want to have the “tot” posts for the category they are tagged with.

    The code is used with a shortcode so that I can insert it in a specific place of the page

    add_shortcode('test-count-post', 'get_current_post_num');
    function get_current_post_num() {
       $url = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
        $curr_post_id = url_to_postid( "https://".$url )
      
      $args = array(
          'post_type' => 'portfolio',
          'post_status' => 'publish',
          'order'=> 'ASC',
          'posts_per_page' => -1
      );
      $portfolio_posts = new WP_Query($args);
    
      if ($portfolio_posts->have_posts()):
          $total_posts = $portfolio_posts->found_posts;
          $num = 1;
         
          while ($portfolio_posts->have_posts()) : $portfolio_posts->the_post();
          $post_id = get_the_ID();
    
          if ($post_id === $curr_post_id) {
              $output= $num . '/' . $total_posts;
          } else {
              $num++;
          }
        endwhile;
      endif;
    return $output;
    } 

    For example, I have 3 posts and the output on post 1 is “1/3”. The output on the second published post is “2/3” etc. Of my test posts, the first 2 have category “xx” and the last one has category “yy”
    So I would like to show, when I am in post 1, “1/2”, while when I am on post 3 -> “1/1”

    To do so I tried to add to my function the following code on line 5 (just after having grabbed the postID)

    $category = get_the_category( $curr_post_id);

    but the var_dump gives me an empty array (while I am expecting the ID of the applied category to that specific post). Later I was planning to add the variable $category to the array of $args, in order to retrieve only the posts within that specific category.

    So my question is: why the $category array appears as empty?

    Moderator bcworkz

    (@bcworkz)

    I assume you’ve assigned one or more categories to the current post ?? Check the value of $curr_post_id. url_to_postid() isn’t 100% reliable. It’s also a more complicated process than necessary to get the current post ID if you’re within a WP loop context. This would almost certainly be the case if this is a shortcode. Within a WP loop, get_the_ID() is a more direct, reliable way to get the current post’s ID.

    If a post has more than one category, it’s ambiguous what post count should be displayed. Count in which category? Or all of them? All of them with all the same categories or all of them with any one of the categories? You’ll need to compose you category count query correctly for the the count you really want.

    Thread Starter elena18

    (@elena18)

    @bcworkz posts have just 1 category.

    I just used the correct function (the one above did not work) as follows

    $category = get_the_category( $curr_post_id->ID);

    It works perfectly (it gives an array with the category), but only if I am in a single blog post.

    However (I am using the Enfold theme) I must apply this function in the single portfolio items, where the array $category comes out empty. I presume that I should go through the terms, as the portfolio item in Enfold is a custom post type (the support is not really of help). But I am not such an expert and I didn’t find a proper solution yet

    Thread Starter elena18

    (@elena18)

    I found the solution. Here the code (working)

    add_shortcode('post-counter', 'get_current_post_num');
    function get_current_post_num() {
      $url = $_SERVER['REQUEST_URI'];
      
      $curr_post_id = url_to_postid( "https://sharkrayareas.org".$url ); //Too early for $post object
      $taxonomy = 'portfolio_entries';
      
      $term_objs = get_the_terms( $curr_post_id->ID, $taxonomy );
    
      foreach ($term_objs as $term_obj)
                   $term_ids = $term_obj->term_id; // get the id from the WP_Term object
    
      
      $args = array(
          'post_type' => 'portfolio',
          'post_status' => 'publish',
          'tax_query' => array(
            array(
              'taxonomy' => 'portfolio_entries',
              'terms'    => $term_ids,
            ),
          ),      
          'order'=> 'ASC',
          'posts_per_page' => -1
      );
      $portfolio_posts = new WP_Query($args);
      
      if ($portfolio_posts->have_posts()):
        echo 'true';
          $total_posts = $portfolio_posts->found_posts;
          
          $num = 1;
         
          while ($portfolio_posts->have_posts()) : $portfolio_posts->the_post();
          $post_id = get_the_ID();
    
          if ($post_id === $curr_post_id) {
              $output= '<div class="count">'. $num . '/' . $total_posts .'</div>';
          } else {
              $num++;
          }
        endwhile;
      endif;
    return $output;
    }

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘How to get number of a post over the total numbers of posts within a category in’ is closed to new replies.