WordPress: associare un'immagine ad una categoria

WordPress: associare un'immagine ad una categoria

WordPress non offre direttamente il modo di associare un'immagine ad una categoria. Tuttavia esiste una soluzione che possiamo implementare da soli.

Il seguente codice, da inserire in functions.php, associa l'URL di un'immagine alle categorie:


<?php

function my_edit_featured_image_category_field( $term ) {
    $term_id = $term->term_id;
    $term_meta = get_option( "taxonomy_$term_id" );         
?>
    <tr class="form-field">
        <th scope="row">
            <label for="term_meta[cat-image]"><?php echo _e( 'URL immagine' ) ?></label>
            <td>
                <input type="text" name="term_meta[cat-image]" id="term_meta[cat-image]" value="<?php echo $term_meta['cat-image']; ?>" />               
            </td>
        </th>
    </tr>
<?php
}

add_action( 'category_edit_form_fields', 'my_edit_featured_image_category_field' );

function my_save_tax_meta( $term_id ){ 
  
        if ( isset( $_POST['term_meta'] ) ) {
             
            $term_meta = array();

           
            $term_meta['cat-image'] = isset ( $_POST['term_meta']['cat-image'] ) ? $_POST['term_meta']['cat-image'] : '';
    
            
            update_option( "taxonomy_$term_id", $term_meta );
     
        } 
} 
    
add_action( 'edited_category', 'my_save_tax_meta', 10, 2 );

add_action( 'category_add_form_fields', 'my_edit_featured_image_category_field' );
add_action( 'create_category', 'my_save_tax_meta', 10, 2 );

Quindi nel frontend del nostro tema possiamo reperire l'URL in questo modo:


// Es. in category.php

$cat = get_the_category();
$term = get_option( 'taxonomy_' . $cat[0]->term_id );
$cat_image = $term['cat-image'];

Torna su