Wordpress: Counts the total number of times tags are used

I successfully updated the existing code to calculate the total number of messages in a specific tag, and then print the amount. I have combined this together based on an existing snippet and although it works, I understand that it is very inefficient.

Ideally, it would be great if I could count the number of messages in all tags and return the total number, so I would not have to make hard codes $term_name.

I know there is a loop somewhere ... This is my first time I really do PHP, so when it is interesting, it reminds me that I have a lot to learn.

<?php
$taxonomy = "post_tag"; // can be category, post_tag, or custom taxonomy name

// Using Term Name
$term_name = 'Cookies';
$term = get_term_by('name', $term_name, $taxonomy);

$term_name1 = 'Juice';
$term1 = get_term_by('name', $term_name1, $taxonomy);

$term_name2 = 'Milk';
$term2 = get_term_by('name', $term_name2, $taxonomy);

// Fetch the count, sum and print.
echo ($term->count + $term1->count + $term2->count);
?>

: , , . . , , , , , 20000 .

+3
1

, , , , , . .

$taxonomy = 'post_tag'; //the post type you want to look up
global $wpdb; //get instance of database connection
$sql = $wpdb->prepare("SELECT terms.name,taxonomy.count
        FROM wp_terms AS terms 
        INNER JOIN wp_term_taxonomy AS taxonomy ON (terms.term_id = taxonomy.term_id)
        WHERE taxonomy = %s;",$taxonomy);
$results = $wpdb->get_results($sql);

if ( $results ){
    foreach ( $results as $result ){
        echo('<p>'.$result->name.' has a count of '.$result->count.'</p>');
    }   
}

: , $wpdb- > "wp _"... , , .

EDIT:

, SQL :

$taxonomy = 'post_tag'; //the post type you want to look up
global $wpdb; //get instance of database connection
$sql = $wpdb->prepare("SELECT sum(taxonomy.count)
        FROM wp_terms AS terms 
        INNER JOIN wp_term_taxonomy AS taxonomy ON (terms.term_id = taxonomy.term_id)
        WHERE taxonomy = %s;",$taxonomy);
$result = $wpdb->get_var($sql);

echo("There are a total of $result tag matches");

. 2 , 3 , 6 ( , ... , ).

+1

All Articles