Avvia un progetto

Mostrare tassonomie personalizzate nel PDF degli articoli WordPress

Offrire un’esperienza chiara e informativa sul tuo sito WordPress spesso significa presentare informazioni dettagliate in modo ordinato. Un modo per migliorarla è mostrare le tassonomie personalizzate nei tuoi articoli WordPress, soprattutto quando questi vengono esportati in PDF. Le tassonomie personalizzate sono uno strumento potente per categorizzare ed etichettare i contenuti in base alle esigenze del tuo sito, che si tratti di prodotti, servizi o qualsiasi altro contenuto.

In questa guida vediamo come mostrare le tassonomie personalizzate nel PDF degli articoli WordPress esportati. La funzione è particolarmente utile per chi deve offrire contenuti scaricabili, come cataloghi prodotti, articoli informativi o guide, in un formato PDF che conserva tutte le categorie e i tag essenziali. Vedremo i passaggi necessari, dalla definizione delle tassonomie personalizzate alla modifica dell’output PDF. Che tu sia alle prime armi con WordPress o uno sviluppatore esperto, questa guida ti aiuterà a migliorare la presentazione e l’usabilità dei contenuti del tuo sito.

Ti serve il nostro plugin WP Posts to PDF. Poi apri il functions.php del tuo child theme e aggiungi il codice qui sotto. Per adattarlo, cambia le chiavi delle tassonomie nella variabile $taxonomies.

// Add a filter to modify the post metadata keys.
add_filter('wordpress_print_posts_meta_keys', function($tmp) {
    global $post; // Access the global post object.
    // Define an array of taxonomy slugs to process.
    $taxonomies = array(
        'vehica_6659'
    );
    // Iterate through each taxonomy.
    foreach($taxonomies as $taxonomy) {
        // Get terms associated with the current post and taxonomy.
        $terms = wp_get_object_terms($post->ID, $taxonomy);
        // Check if any terms are associated.
        if(!empty($terms)){
            // Retrieve the full taxonomy object.
            $taxonomy = get_taxonomy($taxonomy);
            // Initialize an array to store term names.
            $termNames = array();
            foreach($terms as $term){
                // Skip if the term name is not set or is empty.
                if(!isset($term->name) || empty($term->name)) {
                    continue;
                }
                // Add the term name to the array.
                $termNames[] = $term->name;
            }
            // Add a new array to $tmp with taxonomy label and term names.
            $tmp[] = array(
                'key' =>  $taxonomy->label,
                'before' => $taxonomy->label . ': ',
                'value' => implode(',', $termNames), // Combine term names into a string.
            );
        }
    }
    // Return the modified array.
    return $tmp;
});