[英]Thumbnail to external link AND Thumbnail to post
這是我想要完成的
目標A:我想將index.php中的每個縮略圖超鏈接到他們的帖子。 目標B:我想為single.php中的每個縮略圖定義一個到外部網站的超鏈接。
您可能會問為什么我對single.php使用縮略圖? 原因是因為我想要這種布局:
到目前為止,我了解有3種顯示圖像的方法:
我有完成目標A和目標B的代碼,但它們只能分別工作。 換句話說,如果存在“代碼2”,則“代碼1”不起作用。 我該如何解決這個問題? 還是有更好的方法實現我的目標?
代碼1:使用自定義字段(single.php)將縮略圖鏈接到外部網站
<?php $name = get_post_meta($post->ID, 'externalurl', true);
if( $name ) { ?>
<a href="<?php echo $name; ?>"><?php the_post_thumbnail(); ?></a>
<?php } else {
the_post_thumbnail();
} ?>
代碼2:將縮略圖鏈接到帖子(functions.php)
add_filter( 'post_thumbnail_html', 'my_post_image_html', 10, 3 );
function my_post_image_html( $html, $post_id, $post_image_id ) {
$html = '<a href="' . get_permalink( $post_id ) . '" title="' . esc_attr( get_the_title( $post_id ) ) . '">' . $html . '</a>';
return $html;
}
is_single()函數將幫助您實現所需的功能。 嘗試下面的functions.php中的代碼,並從single.php中刪除其他代碼
function my_post_image_html( $html, $post_id, $post_image_id ) {
if ( is_single()) {
$name = get_post_meta($post_id, 'externalurl', true);
if( $name ) {
$html = '<a href="'.$name.'" title="' . esc_attr( get_the_title( $post_id ) ) . '">' . $html . '</a>';
}
return $html;
}
else
{
$html = '<a href="' . get_permalink( $post_id ) . '" title="' . esc_attr( get_the_title( $post_id ) ) . '">' . $html . '</a>';
return $html;
}
}
add_filter( 'post_thumbnail_html', 'my_post_image_html', 10, 3 );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.