Mostrare thumbnail per le categorie?

15 apr 2013, 15:54:52
Visualizzazioni: 17.6K
Voti: 2

Attualmente ho un codice nel mio category.php che verifica se una categoria specifica ha sottocategorie e, nel caso, le mostra usando wp_list_categories.

Vorrei che queste wp_list_categories mostrassero delle thumbnail, quindi ho creato un nuovo walker, ma non riesco a capire come mostrare le miniature.

Andrebbe bene anche mostrare l'immagine in evidenza del mio ultimo custom post type in questa categoria, oppure usare un plugin.

Attualmente ho il seguente walker nel mio functions.php:

class Walker_Category_Parents extends Walker_Category {

function start_el(&$output, $category, $depth, $args) {
    global $wpdb;
    extract($args);

    $link2 = ''.$category->slug.'';
    $cat_name = esc_attr( $category->name );
    $cat_name = apply_filters( 'list_cats', $cat_name, $category );
    $link = '<a href="' . esc_attr( get_term_link($category) ) . '" ';
    $link .= 'title="' . esc_attr( strip_tags( apply_filters( 'category_description', $category->description, $category ) ) ) . '"';
    $link .= 'rel="'.$category->slug.'" ';
    $link .= '>';
    $link .= $cat_name . '</a>';
    if ( 'list' == $args['style'] ) {
        $output .= "\t<li";

        $children = $wpdb->get_results( "SELECT term_id FROM $wpdb->term_taxonomy WHERE parent=".$category->term_id );

        $children_count = count($children);

        $has_children = ($children_count != 0) ? ' parent-category' : '';

        $class = 'cat-item cat-item-' . $category->term_id . $has_children;
        if ( !empty($current_category) ) {
            $_current_category = get_term( $current_category, $category->taxonomy );
            if ( $category->term_id == $current_category )
                $class .=  ' current-cat';
            elseif ( $category->term_id == $_current_category->parent )
                $class .=  ' current-cat-parent';
        }
        $output .=  ' class="' . $class . '"';
        $output .= ">$link\n";
        $output .= "<img src='http://localhost/wp-content/themes/vom13/images/producten/";
        $output .= "$link2.png'>\n";
    } else {
        $output .= "\t$link<br />\n";
    }
}

}

Come puoi vedere, attualmente cerca l'immagine in una cartella, ma questo non è assolutamente ideale, perché non sono l'unico ad aggiungere categorie, ma non voglio dare a tutti l'accesso FTP.

Qualche soluzione?

Grazie!

0
Tutte le risposte alla domanda 2
3

C'è un ottimo plugin chiamato Taxonomy Images. Ti permette di impostare un'immagine per categoria che poi puoi accedere in vari modi.

È un po' particolare perché utilizza alcuni filtri personalizzati per restituire le immagini, ma la documentazione è abbastanza buona e dovresti essere in grado di capirla.

== AGGIORNAMENTO == Ecco un rapido esempio che ottiene l'immagine basandosi sull'ID (suppongo che tu abbia già l'oggetto $category nel tuo snippet):

$images = get_option('taxonomy_image_plugin');
$cat_id = $category->term_taxonomy_id;
if( array_key_exists( $cat_id, $images ) ) {
    echo wp_get_attachment_image( $images[$cat_id] );
}

Ecco una versione leggermente ampliata di quel codice nei forum di supporto.

15 apr 2013 18:42:43
Commenti

Grazie! Ho esaminato questo plugin, ma non sono riuscito a capire come ottenere questo risultato, e non ero sicuro che fosse possibile. Ci darò un'altra occhiata.

user31532 user31532
16 apr 2013 10:03:04

Grazie ancora per la modifica! Ora mostra tutte le immagini, solo non nella posizione in cui vorrei che fossero. (Ma immagino che questo dovrebbe essere abbastanza facile da sistemare.)

user31532 user31532
17 apr 2013 16:39:17

Non è proprio bello dover caricare un plugin per fare questo. So che è un thread vecchio, ma la mia raccomandazione è di scaricare il plugin Taxonomy Images come suggerito sopra, aprire il codice, e copiare ciò che ti serve nel tuo progetto. In questo modo non avrai tutto il "peso" delle impostazioni della pagina del plugin e così via. WordPress dovrebbe davvero renderlo una funzionalità predefinita/standard.

mrwpress mrwpress
4 feb 2020 20:49:58
0

Penso che il modo migliore sia permettere all'amministratore di scegliere l'immagine in evidenza per una categoria dalla Libreria Media. Questo è ciò che fa WooCommerce per le categorie di prodotti. Ho controllato come WooCommerce implementa questa funzionalità (in includes/admin/class-wc-admin-taxonomies.php) ed ecco il codice riutilizzabile (usalo in functions.php o nel tuo plugin personalizzato). Può essere utilizzato con le tassonomie dei custom post type.

<?php
/* Miniature immagine per categoria */

/* Se è un CPT, usa gli script e gli stili per visualizzare il popup della Libreria Media */
function media_uploader() {
    global $post_type;
    if( 'YOUR_CUSTOM_POST_TYPE' == $post_type) {
        if(function_exists('wp_enqueue_media')) {
            wp_enqueue_media();
        }
        else {
            wp_enqueue_script('media-upload');
            wp_enqueue_script('thickbox');
            wp_enqueue_style('thickbox');
        }
    }
}
add_action('admin_enqueue_scripts', 'media_uploader');

/* Mostra il campo del form */

add_action( 'YOUR_CUSTOM_POST_TYPE-category_add_form_fields', 'add_image_field', 10, 2 );
add_action( 'YOUR_CUSTOM_POST_TYPE-category_edit_form_fields', 'add_image_field', 10, 2 );
function add_image_field($taxonomy) {
    if(is_object($taxonomy)) // modifica termine non aggiungi termine
    $selectedimgid = get_term_meta( $taxonomy->term_id, 'YOUR_CUSTOM_POST_TYPE_cat_thumbnail_id', true );
    
    ?>
    <div class="form-field term-thumbnail-wrap">
        <label>Miniatura</label>
        <div id="YOUR_CUSTOM_POST_TYPE_cat_thumbnail" style="float: left; margin-right: 10px;"><img src="<?php if(isset($selectedimgid)) echo wp_get_attachment_image_src($selectedimgid)[0]; else echo "PLACEHOLDER-IMAGE-HERE.jpg";?>" width="60px" height="60px" /></div>
        <div style="line-height: 60px;">
            <input type="hidden" id="YOUR_CUSTOM_POST_TYPE_cat_thumbnail_id" name="YOUR_CUSTOM_POST_TYPE_cat_thumbnail_id" value="<?php if(isset($selectedimgid)) echo $selectedimgid; ?>" />
            <button type="button" class="upload_image_button button">Carica/Aggiungi immagine</button>
            <button type="button" class="remove_image_button button">Rimuovi immagine</button>
        </div>
        <script type="text/javascript">

            // Mostra il pulsante "rimuovi immagine" solo quando necessario
            if ( ! jQuery( '#YOUR_CUSTOM_POST_TYPE_cat_thumbnail_id' ).val() ) {
                jQuery( '.remove_image_button' ).hide();
            }

            // Caricamento file
            var file_frame;

            jQuery( document ).on( 'click', '.upload_image_button', function( event ) {

                event.preventDefault();

                // Se il frame media esiste già, riaprirlo
                if ( file_frame ) {
                    file_frame.open();
                    return;
                }

                // Crea il frame media
                file_frame = wp.media.frames.downloadable_file = wp.media({
                    title: 'Scegli un\'immagine',
                    button: {
                        text: 'Usa immagine'
                    },
                    multiple: false
                });

                // Quando un'immagine è selezionata, esegui una callback
                file_frame.on( 'select', function() {
                    var attachment           = file_frame.state().get( 'selection' ).first().toJSON();
                    var attachment_thumbnail = attachment.sizes.thumbnail || attachment.sizes.full;

                    jQuery( '#YOUR_CUSTOM_POST_TYPE_cat_thumbnail_id' ).val( attachment.id );
                    jQuery( '#YOUR_CUSTOM_POST_TYPE_cat_thumbnail' ).find( 'img' ).attr( 'src', attachment_thumbnail.url );
                    jQuery( '.remove_image_button' ).show();
                });

                // Infine, apri la modale
                file_frame.open();
            });

            jQuery( document ).on( 'click', '.remove_image_button', function() {
                jQuery( '#YOUR_CUSTOM_POST_TYPE_cat_thumbnail' ).find( 'img' ).attr( 'src', 'PLACEHOLDER-IMAGE-HERE.jpg' );
                jQuery( '#YOUR_CUSTOM_POST_TYPE_cat_thumbnail_id' ).val( '' );
                jQuery( '.remove_image_button' ).hide();
                return false;
            });

            jQuery( document ).ajaxComplete( function( event, request, options ) {
                if ( request && 4 === request.readyState && 200 === request.status
                    && options.data && 0 <= options.data.indexOf( 'action=add-tag' ) ) {

                    var res = wpAjax.parseAjaxResponse( request.responseXML, 'ajax-response' );
                    if ( ! res || res.errors ) {
                        return;
                    }
                    // Pulisci i campi miniatura al submit
                    jQuery( '#YOUR_CUSTOM_POST_TYPE_cat_thumbnail' ).find( 'img' ).attr( 'src', 'PLACEHOLDER-IMAGE-HERE.jpg' );
                    jQuery( '#YOUR_CUSTOM_POST_TYPE_cat_thumbnail_id' ).val( '' );
                    jQuery( '.remove_image_button' ).hide();
                    // Pulisci il campo tipo di visualizzazione al submit
                    jQuery( '#display_type' ).val( '' );
                    return;
                }
            } );

        </script>
        <div class="clear"></div>
    </div>
    <?php
    
}
7 ago 2021 17:24:30