PROJET AUTOBLOG


Planet-Libre

source: Planet-Libre

⇐ retour index

Progi1984 : WordPress : Ajouter une image aux catégories

lundi 24 juin 2013 à 10:30

Avec WordPress, la personnalisation d’un site peut aller très loin. Dans cet article, nous allons parler images, articles et catégories.
Voici l’état des lieux :

Comment allons nous faire ?

Toutes les modifications se font dans le fichier functions.php de votre thème WordPress.

Activer le support des images à la une dans le thème WordPress

On active les miniatures pour les articles.

add_theme_support('post-thumbnails', array('post'));

On définit les tailles des miniatures

set_post_thumbnail_size(100, 100);

Désormais, nous avons, pour les articles, la possibilité d’avoir une image à la une.

Lier une image à une catégorie

On crée un hook pour s’intégrer au formulaire d’édition de la catégorie dans le BO WordPress :

function fnAction_edit_category_form_fields($poTag){
  $arrCategoryImages = get_option('category_url_images');
  if(is_array($arrCategoryImages) && array_key_exists($poTag->term_id, $arrCategoryImages)){
    $psURL = $arrCategoryImages[$poTag->term_id] ;
  } else {
    $psURL = '';
  }
  ?>
  

On crée un hook qui s’activera lors de la sauvegarde d’une catégorie :

function fnAction_edited_category($piIDTerm){
  if(isset($_POST['category_url_image'])){
    $arrCategoryImages = get_option('category_url_images');
    $arrCategoryImages[$piIDTerm] = $_POST['category_url_image'];
    update_option('category_url_images', $arrCategoryImages);
  }
}
add_action('edited_category', 'fnAction_edited_category');

Récupérer l’image à la une ou l’image de la catégorie

Pour cela, j’ai crée une fonction qui retourne d’abord si elle est présente l’image à la une sinon l’image liée à la catégorie.

function fnWP_getOGImage(){
  if((function_exists('has_post_thumbnail')) && (has_post_thumbnail())) { 
    $imageData = wp_get_attachment_image_src(get_post_thumbnail_id (get_the_ID()), 'thumbnail');
    return $imageData[0];
  } else {
    $oCategory = get_the_category(get_the_ID());
    if($oCategory){
      $arrCategoryImages = get_option('category_url_images');
      if(is_array($arrCategoryImages) && array_key_exists($oCategory[0]->term_id, $arrCategoryImages)){
        return $arrCategoryImages[$oCategory[0]->term_id] ;
      } else {
        return '';
      }
    }
  }
  return '';
}

Désormais, à vous de jouer ! Dans mon cas, j’ai intégré cela dans mon header pour gérer les og:image de Facebook.

Cet article WordPress : Ajouter une image aux catégories est apparu en premier sur RootsLabs.

Gravatar de Progi1984
Original post of Progi1984.Votez pour ce billet sur Planet Libre.