A
A
arkanzas752020-11-14 13:36:34
WordPress
arkanzas75, 2020-11-14 13:36:34

How to make a post counter in Wordpress?

I'm trying to make a count of posts that are already tied to a specific post_type. This uses custom fields.

<?php
            $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
            $args = array(
                'posts_per_page' => 8,
                'order'   => 'DESC',
                'post_type'   => 'realtors',
                'paged'          => $paged,
            );
            $the_query = new WP_Query($args);
            
            if ($the_query->have_posts()) :
                while ($the_query->have_posts()) : $the_query->the_post(); 
                $agent_id = get_the_ID();
                $meta_query[] = array(
                    'key'		=> 'realtor-id',
                    'value'		=> $agent_id,
                    'compare'	=> '='
                    );
            
             $objcount = new WP_Query(array(
             'post_type' => array( 'apartment', 'exclusive-objects' ),
             'posts_per_page' => 999999,
             'meta_query' => $meta_query
             )); ?>
                    
        <p>К риелтору <?php the_title(); ?> привязано <?php echo $objcount->post_count; ?> объекта</p></div>

            <?php

                endwhile;
            endif;

            ?>
        <?php wp_reset_query(); ?>


As I understand it, at the current location, $meta_query is filled with each round of the loop and I get incorrect data. If $meta_query is taken out of the loop, then 'value' => $agent_id does not include the post ID and there is no data at all. In general, tell me how to properly put everything in its place ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Zolin, 2020-11-14
@arkanzas75

Your logic is clearly broken somewhere, there shouldn't be so many heavy queries. As an intermediate solution, you can use get_posts()to not overwrite the $post global variable and only get the post id to shorten the query:

$objcount = get_posts( array(
  'numberposts' => -1,
  'post_type' => array( 'apartment', 'exclusive-objects' ),
  'fields' => 'ids',
  'meta_query' => array(
    array(
      'key' => 'realtor-id',
      'value' => get_the_ID(),
      'compare'	=> '='
    )
  )
) );

echo count($objcount);

But for good, you need to rewrite the part where the object is added so that the attached objects are stored in the realtor's meta

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question