web-dev-qa-db-fra.com

Comment afficher l'image sélectionnée CAPTION uniquement si elle existe

J'utilise cette fonction dans le fichier functions.php pour afficher la légende des images faeturées:

function the_post_thumbnail_caption() {
global $post;

$thumbnail_id    = get_post_thumbnail_id($post->ID);
$thumbnail_image = get_posts(array('p' => $thumbnail_id, 'post_type' => 'attachment'));

if ($thumbnail_image && isset($thumbnail_image[0])) {
echo '<div class="front-caption">'.$thumbnail_image[0]->post_excerpt.'</div>';
}
} 

Et en utilisant cela dans le fichier modèle pour afficher la légende:

<?php 
if (the_post_thumbnail_caption()) { 
 the_post_thumbnail_caption(); 
}
?>

Dans le fichier de fonctions, la légende s'affiche dans une classe div = "légende-avant" que je stylise avec des bordures. Si la légende n'existe pas, il affiche toujours le div bordé vide.

Si aucune légende n'existe, je ne souhaite pas afficher le div bordé. Je veux juste que rien ne s'affiche.

Comment puis-je coder correctement pour que cela fonctionne? Merci d'avance.

1
Paul Coppock

Je suis "un peu en retard" mais cette solution a très bien fonctionné pour moi. Il ne montrera la div que si la légende n'est pas vide.

<?php
$get_description = get_post(get_post_thumbnail_id())->post_excerpt;
the_post_thumbnail();
  if(!empty($get_description)){//If description is not empty show the div
  echo '<div class="featured_caption">' . $get_description . '</div>';
  }
?>
3
Dejo Dekic

Vous pouvez essayer ceci:

function the_post_thumbnail_caption() {
 global $post;

 $thumbnail_id    = get_post_thumbnail_id($post->ID);
 $thumbnail_image = get_posts(array('p' => $thumbnail_id, 'post_type' => 'attachment'));

  if ($thumbnail_image && isset($thumbnail_image[0])) {
   return '<div class="front-caption">'.$thumbnail_image[0]->post_excerpt.'</div>';
  } else {
    return;
  }
} 

et alors :

echo the_post_thumbnail_caption(); 
2
JMau

Veuillez noter que depuis WordPress 4.6, la fonction a été ajoutée au noyau (/wp-includes/post-thumbnail-template.php).

L'utilisation du code précédemment publié ici provoquera l'erreur:

Erreur fatale: impossible de redéclarer the_post_thumbnail_caption ()

Pour éviter cela, veuillez nommer la fonction autrement ou, si vous utilisez des versions antérieures de WordPress dans un thème, cochez la case suivante:

if ( ! function_exists( 'the_post_thumbnail_caption' ) ) {
 function the_post_thumbnail_caption() {
  global $post;

  $thumbnail_id    = get_post_thumbnail_id($post->ID);
  $thumbnail_image = get_posts(array('p' => $thumbnail_id, 'post_type' => 'attachment'));

   if ($thumbnail_image && isset($thumbnail_image[0])) {
    return '<div class="front-caption">'.$thumbnail_image[0]->post_excerpt.'</div>';
   } else {
     return;
   }
 }
}
2
Mere Development