Wordpress: how to display the number of posts on the author’s page on a custom taxonomy

I am trying to show a custom taxonomy on the author’s page using a counter, but I don’t seem to know how to do this.

I have code in a .php function

add_action( 'pre_get_posts', function ( $q ) { if( !is_admin() && $q->is_main_query() && $q->is_author() ) { $q->set( 'posts_per_page', 100 ); $q->set( 'post_type', 'custom_feedback' ); } }); 

and on my author page:

 <div class="feedback-respond"> <h3 class="feedback-title">User Feedback </h3> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php the_content(); ?> <?php endwhile; else: ?> <p><?php _e('No posts by this author.'); ?></p> <?php endif; ?> </div> 

The code works for the entire author’s profile, but I don’t know how to make the custom taxonomy appear as follows:

User reviews

6 POSITIVE feedback 4 NEGATIVE feedback

all feedback goes here

all feedback goes here

all feedback goes here

By the way, this is a custom post type (custom_feedback) and a custom taxonomy (feedback_taxonomy) with two categories, Positive and Negative.

Help the masters?

+6
source share
1 answer

The only way to achieve this is to run two separate requests and count the messages returned from two separate requests. We will use get_posts , since get_posts already passes several important default values ​​to WP_Query to make the query faster and more performance-oriented.

We will add one huge temporary and resource saver to the request, 'fields' => 'ids' . What this does is it only retrieves the post tags, not the full post object. This can reduce the request time of queries and db by 99%, therefore, despite the fact that you will run 2 separate queries in a full database, the page performance loss will be imperceptible.

Let's put everything in code (this is included in author.php, and note: this code is not verified and it requires at least PHP 5.4 +)

 $author_id = get_queried_object_id(); // Gets the author id when viewing the author page // Add our term slugs into an array. $terms = ['positive', 'negative']; // Just make sure these values are correct $count = []; foreach ( $terms as $term ) { // Build our query $args = [ 'nopaging' => true, 'post_type' => 'custom_feedback', 'author' => $author_id, 'tax_query' => [ [ 'taxonomy' => 'feedback_taxonomy', 'field' => 'slug', 'terms' => $term ], ], 'fields' => 'ids' ]; $q = get_posts( $args ); // Count the amount of posts and add in array $count[$term] = count( $q ); } // Display our text with post counts, just make sure your array keys correspond with your term slugs used $positive = ( isset( $count['positive'] ) ) ? $count['positive'] : 0; $negative =( isset( $count['negative'] ) ) ? $count['negative'] : 0; echo $positive . ' POSITIVE feedback ' . $negative . ' NEGATIVE feedback'; 
+1
source

Source: https://habr.com/ru/post/989881/


All Articles