Conteggio articoli in una tassonomia personalizzata

15 dic 2012, 19:02:36
Visualizzazioni: 47.9K
Voti: 11

Esiste un modo per contare tutti gli articoli pubblicati da una tassonomia personalizzata?

Cercando in giro ho trovato questo snippet ma non sono riuscito a farlo funzionare...

global $wpdb;
$query = "
        SELECT COUNT( DISTINCT cat_posts.ID ) AS post_count
        FROM wp_term_taxonomy AS cat_term_taxonomy INNER JOIN wp_terms AS cat_terms ON
        cat_term_taxonomy.term_id = cat_terms.term_id
        INNER JOIN wp_term_relationships AS cat_term_relationships 
        ON cat_term_taxonomy.term_taxonomy_id = cat_term_relationships.term_taxonomy_id
        INNER JOIN wp_posts AS cat_posts 
        ON cat_term_relationships.object_id = cat_posts.ID
        WHERE cat_posts.post_status = 'publish' 
        AND cat_posts.post_type = 'post' 
        AND cat_term_taxonomy.taxonomy = 'TUA-TASSONOMIA-PERSONALIZZATA' 
        AND cat_terms.slug IN ('SLUG-TERMINE-1, SLUG-TERMINE-2')
    ";
return $wpdb->get_var($query);
0
Tutte le risposte alla domanda 10
2

Utilizza un'istanza di WP_Query per interrogare il database. http://codex.wordpress.org/Class_Reference/WP_Query

Per interrogare il database per tassonomie personalizzate usa:

$query = new WP_Query( array( 'people' => 'bob' ) );

Per maggiori dettagli sulle opzioni disponibili vedi: Parametri della Tassonomia http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

Recupera i post pubblicati utilizzando

'post_status' => 'publish'

Usa found_posts per recuperare il numero di post

$count = $query->found_posts;
15 dic 2012 19:32:09
Commenti

Non dimenticare di usare wp_reset_postdata().

amarinediary amarinediary
20 mar 2021 14:08:05

@amarinediary in questo caso in realtà non devi resettare i dati del post. Devi farlo solo se fai il loop dei post e usi $query->the_post(); che sovrascriverà l'oggetto globale $post del loop. Se stai solo ottenendo dei conteggi, resettare i dati del post è solo un calcolo in più.

noahmason noahmason
28 feb 2023 21:34:33
0
function wp_get_productcat_postcount($id) {

    //ritorna $count;
    $args = array(
      'post_type'     => 'product', //tipo di post, ho usato 'product'
      'post_status'   => 'publish', // cerca tutti i post pubblicati
      'posts_per_page' => -1,  //mostra tutti
      'tax_query' => array(
        'relation' => 'AND',
        array(
          'taxonomy' => 'product_cat',  //nome della tassonomia qui, ho usato 'product_cat'
          'field' => 'id',
          'terms' => array( $id )
        )
      )
    );

    $query = new WP_Query( $args);

    /*
    echo '<pre>';

    print_r($query->post_count);
    echo '</pre>';
    */

    return (int)$query->post_count;

}
24 apr 2013 14:46:14
0

Mi piace molto la semplicità della risposta di Varsha Dhadge, ma quella è per i termini di tassonomia collegati a un post specifico. Per l'intero sito, usa invece get_terms in modo simile:

$custom_cats = get_terms(
    'custom_cat', // il tuo slug della tassonomia personalizzata
    array(
        // ottieni tutti i termini, anche quelli vuoti così possiamo vedere quali elementi hanno 0
        'hide_empty' => false,
    )
);

foreach ( $custom_cats as $term ) {
    echo $term->slug . ' - ' . $term->count . '<br>';
}
14 lug 2020 03:59:46
2

Il codice seguente otterrà il conteggio degli articoli da una particolare tassonomia

<?php 
  $terms = get_the_terms( $post->ID , 'your-taxonomy' );
  foreach ( $terms as $term ) {
    echo $term->count;
  } ?>
15 nov 2017 14:29:48
Commenti

questo ottiene solo i termini associati a $post->ID. vedi la mia soluzione che utilizza get_terms invece.

squarecandy squarecandy
14 lug 2020 04:01:14

Nota che $term->count ti dà comunque il conteggio totale dei post che usano quel termine nell'intero sito - ma otterrai solo i termini associati al post corrente. Forse è quello che alcune persone cercano qui, ma se vuoi tutti i termini nell'intero sito - che è la domanda dell'OP - hai bisogno di get_terms.

squarecandy squarecandy
14 lug 2020 04:07:50
1

Puoi farlo con l'oggetto corrente utilizzando get_queried_object()

$posts = get_queried_object();
echo $posts->count;

Altrimenti potresti eseguire inutilmente una seconda query, giusto?

18 ago 2014 22:40:43
Commenti

Fantastico! :) Grazie mille. Funziona perfettamente quando sono all'interno di una categoria. :)

Woppi Woppi
31 mag 2017 12:50:08
0

WordPress aggiunge un attributo di conteggio a ogni tassonomia e lo aggiorna ogni volta che viene inserito o aggiornato un nuovo articolo. Questo perché non vuole accedere nuovamente al database e fare calcoli per ottenere il conteggio degli articoli nella tassonomia.

echo $custom_tax_obj->count;
3 feb 2014 00:06:43
0

Mi trovo di fronte a questa situazione nei template degli archivi delle tassonomie (ad esempio taxonomy-taxname.php) per un sito con un custom post type e relative tassonomie di categoria/tag. Volevo nell'header visualizzare un conteggio di quanti elementi utilizzavano la tassonomia.

Nei miei template di archivio delle tassonomie, avevo bisogno di trovare il termine rappresentato dalla tassonomia, per poi passarlo a una funzione che ottenesse il numero di elementi del custom post type che utilizzavano quel termine, in questo caso dalla tassonomia dei tag

// il termine di cui abbiamo bisogno per questa tassonomia
$term_obj = get_queried_object(); 

// ottieni l'oggetto term
$term = get_term( $term_obj->term_id, 'taxname' );

// ottieni il conteggio dei contenuti con questo termine
$tax_count = get_tax_count('taxname', $term->slug, 'custom-post-type-name');

// la grammatica conta
$plural = ( $tax_count == 1) ? '' : 's';

echo $tax_count . ' Elemento' . $plural . ' Contrassegnato "' . $term->name . '"';

La funzione per effettuare il conteggio utilizza WP_Query con un tax_query:

function tax_count ( $taxonomy, $term, $post_type ) {
    // trova il numero di elementi nel custom post type che usano il termine in una tassonomia

    $args = array(
        'post_type' =>  $post_type,
        'posts_per_page' => -1,
        'tax_query' => array(
            array(
                'taxonomy' => $taxonomy,
                'field'    => 'slug',
                'terms'    => $term,
            ),
        ),
    );

    $tax_query = new WP_Query( $args );

    return ($tax_query->found_posts);

}
20 set 2018 08:19:18
1
-1
$args = array(
'post_type' => 'product',
'post_status' => 'published',
'product_cat' => $catpage, // $catpage == slug della tua categoria
'numberposts' => -1
);
echo $num = count( get_posts( $args ) );
24 ago 2016 16:23:48
Commenti

Per favore, prenditi un minuto e spiega cosa fa il tuo codice.

user9447 user9447
24 ago 2016 16:46:27
0
-1

Ho creato questa funzione per la mia esigenza e corrisponde esattamente a questa domanda.

Ottieni il conteggio dei post dentro o fuori da una tassonomia

/**
 * Ottieni il conteggio dei Post/Tipi di Post nella tassonomia specificata
 *
 * @param  $post_type string qualsiasi post type
 * @param  $taxonomy string qualsiasi tassonomia
 * @param  $is_exists string NOT EXISTS o EXISTS
 *
 * @return String Numero di Post contati
 */

function prefix_get_post_count_in_taxonomy($post_type, $taxonomy, $is_exists = 'NOT EXISTS')
{
    global $wpdb;

    $count = $wpdb->get_var(
        "
select COUNT(*) as post_count  
    FROM $wpdb->posts as A 
WHERE $is_exists (
    SELECT 1
    FROM 
         $wpdb->term_relationships as B
             INNER JOIN $wpdb->term_taxonomy as C
                 ON C.term_taxonomy_id = B.term_taxonomy_id
    WHERE C.taxonomy = '$taxonomy'
      AND B.object_id = A.ID
    )                                                    
  AND A.post_type = '$post_type'
  "
    );

    return $count;
}


/**
 * Esempio
 *
 * Post type: download
 * Taxonomy: download_category
 * Is Exist: EXISTS
 */
echo prefix_get_post_count_in_taxonomy('download', 'download_category', 'EXISTS');
17 mag 2021 12:33:41
0
-1

Questo metodo che ho seguito ha funzionato per me.

 $terms = get_terms([
    'taxonomy' => 'types',
    'hide_empty' => false,
]);
$taxonomies = [];

foreach($terms as $term){
    echo $term->name .'----->'.$term->count.'<br>';  //qui restituisce il conteggio dei post.
}
1 dic 2022 15:06:06