简体   繁体   English

外部链接的缩略图和发布的缩略图

[英]Thumbnail to external link AND Thumbnail to post

Here is what I'd like to accomplish 这是我想要完成的

Goal A: I want to hyperlink each thumbnail in index.php to their post. 目标A:我想将index.php中的每个缩略图超链接到他们的帖子。 Goal B: I want to define a hyperlink for each thumbnail in single.php to an external website. 目标B:我想为single.php中的每个缩略图定义一个到外部网站的超链接。

You may ask why am I using thumbnails for single.php? 您可能会问为什么我对single.php使用缩略图? The reason is because I want this layout: 原因是因为我想要这种布局:

在此处输入图片说明

And so far I understand that there are 3 methods to display images: 到目前为止,我了解有3种显示图像的方法:

  1. Insert image into the editor area along with the text, but the problem is I cannot float the image and text differently because all items within a post are assigned ap tag - am I wrong? 将图像与文本一起插入编辑器区域,但是问题是我不能以不同的方式浮动图像和文本,因为帖子中的所有项目都分配了ap标签-我错了吗?
  2. Custom fields should get the job done but it doesn't seem the most efficient way - or am I wrong? 自定义字段应该可以完成工作,但这似乎不是最有效的方法-还是我错了?
  3. Post Thumbnails should be the easiest way but see my problem below 发布缩略图应该是最简单的方法,但是请在下面查看我的问题

I have the code to accomplish Goal A and B but they only work separately. 我有完成目标A和目标B的代码,但它们只能分别工作。 In other words, "Code 1" does not work if "Code 2" is present. 换句话说,如果存在“代码2”,则“代码1”不起作用。 How can I resolve this issue? 我该如何解决这个问题? Or is there a better method accomplish my goal? 还是有更好的方法实现我的目标?

Code 1: Link thumbnails to external websites using custom field (single.php) 代码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();
} ?>

Code 2: Link thumbnails to the post (functions.php) 代码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() function will help you achieve what you need. is_single()函数将帮助您实现所需的功能。 Try below code in functions.php and remove the additional code from single.php 尝试下面的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM