Wednesday, May 12, 2021
More

    Latest Posts


    10 Ways to Get More Web Design Clients, Fast!

    Affect an image to categories in WordPress without plugin

    - Advertisement -backlink tools

    This tutorial allows you to add a text field to fill the URL of an image for each of your categories.

    - Advertisement -

    Add this in your functions.php file:

    - Advertisement -
    add_action('init', 'my_category_module');
    - Advertisement -
    function my_category_module() {
     add_action ( 'edit_category_form_fields', 'add_image_cat');
     add_action ( 'edited_category', 'save_image');
     }

    The function to add the extra field :

    function add_image_cat($tag){
     $category_images = get_option( 'category_images' );
     $category_image = '';
     if ( is_array( $category_images ) && array_key_exists( $tag->term_id, $category_images ) ) {
     $category_image = $category_images[$tag->term_id] ;
     }
     ?>
     <tr>
     <th scope="row" valign="top"><label for="auteur_revue_image">Image</label></th>
     <td>
     <?php
     if ($category_image !=""){
     ?>
     <img src="<?php echo $category_image;?>" alt="" title=""/>
     <?php
     }
     ?>
     <br/>
     <input type="text" name="category_image" id="category_image" value="<?php echo $category_image; ?>"/><br />
     <span>This field allows you to add a picture to illustrate the category. Upload the image from the media tab WordPress and paste its URL here.</span>
     </td>
     </tr>
     <?php
     }

    Function to save :

    function save_image($term_id){
     if ( isset( $_POST['category_image'] ) ) {
     //load existing category featured option
     $category_images = get_option( 'category_images' );
     //set featured post ID to proper category ID in options array
     $category_images[$term_id] =  $_POST['category_image'];
     //save the option array
     update_option( 'category_images', $category_images );
     }
     }
    }
    

    To display the image put this in “category.php” or “archive.php” depending on your theme, it’s better to choose “category.php”,  and add this code before the WordPress loop :
    :

    <?php
     if(is_category()){
     $category_images = get_option( 'category_images' );
     $category_image = '';
     if ( is_array( $category_images ) && array_key_exists( get_query_var('cat'), $category_images ) ){
    
    $category_image = $category_images[get_query_var('cat')] ;
     ?>
     <img src="<?php echo $category_image;?>"/>
     <?php
     }
     }
     ?>
    

    Before applying the changes in this tutorial, make sure your WordPress hosting provider you are using is good enough to offer the right amount of bandwidth that can support the new changes.

    - Advertisement -

    Latest Posts




    Don't Miss


    300x250_trinka_tagline

    Stay in touch

    To be updated with all the latest news, offers and special announcements.