建站教程

建站教程

Products

当前位置:首页 > 建站教程 >

给wordpress添加函数,修改文章图片链接指向,避免出现404错误(WordPress主题开发时相关产品调用代码是什么?)

GG网络技术分享 2025-03-18 16:13 0


给wordpress添加函数,修改文章图片链接指向,避免出现404错误

最近,我的wordpress网站出现了一个小问题——点击文章内容中的图片,会跳出404错误页面(如下图),这是怎么回事?为什么没有指向原图的链接?该怎样解决这个问题?

404错误页面

解决方法无非有2种:去掉图片链接或修改图片链接地址。我们都知道,百度等搜索引擎都特别喜欢图片,在我们的文章被收录后,如果文章内容中的图片都带有原图的链接,那么,这些原图也有可能被搜索引擎收录。所以,我决定:还是把wordpress网站文章内容中的图片链接修改成原图的链接。

我们将下面这段代码放到wordpress网站当前主题模板的functions.php文件中,如下图:

//文章内容中的图片 自动 链接 原图链接

function auto_post_link($content) {

global $post;

$content = preg_replace('/<a href=\\s*(\\'|\\")(.*?)<\\s*img\\s+[^>]*?src\\s*=\\s*(\\'|\\")(.*?)\\\\1[^>]*?\\/?\\s*><\\/a>/i', "<a target=\\"_blank\\" href=\\"$4\\" title=\\"".$post->post_title."\\" ><img src=\\"$4\\" /></a>", $content);

return $content;

}

add_filter ('the_content', 'auto_post_link',0);

修改图片链接的代码

​这里创建了一个auto_post_link()函数,函数中通过preg_replace()函数把文章内容中的图片链接相关的字符替换成我们想要的字符,这个preg_replace()有3个参数,第一个参数是正则表达式,用于匹配文章内容中的图片链接相关字符;第二个参数是替换后的内容;第三个参数是文章内容变量。参数2中的$4,代表参数1中的第4个小括号的匹配内容。

add_filter ('the_content', 'auto_post_link',0) 这句代码表示:在wordpress网站打开文章页面时,每调用一次文章内容,就会调用一次auto_post_link()函数。

通过上面的操作,wordpress网站的文章内容中的图片链接就都修改成了原图片的链接,我们在点击这些图片时,就会在浏览器中打开原图片,再也不会出现404错误页面的情况了。如有疑问,欢迎在下面点评。记得关注我哦,后面还会有更多的精彩内容。

WordPress主题开发时相关产品调用代码是什么?

我们用wordpress开发企业主题的时候,如果有产品展示模块,那在浏览产品详情页的时候,我们经常会看到产品详情底部有一个相关产品显示。其实对于这个模块我们并不陌生,因为在我们写文章详情页的时候,也写过调用当前文章的相关文章代码,WordPress主题开发时相关产品调用代码是什么?今天一起了解一下。

<?php

//get the taxonomy terms of custom post type

$customTaxonomyTerms = wp_get_object_terms( $post->ID, \'product_category\', array(\'fields\' => \'ids\') );

//query arguments

$args = array(

\'post_type\' => \'products\',

\'post_status\' => \'publish\',

\'posts_per_page\' => 4,

\'orderby\' => \'rand\',

\'tax_query\' => array(

array(

\'taxonomy\' => \'product_category\',

\'field\' => \'id\',

\'terms\' => $customTaxonomyTerms

)

),

\'post__not_in\' => array ($post->ID),

);

//the query

$relatedPosts = new WP_Query( $args );

//loop through query

if($relatedPosts->have_posts()){

echo \'<div class=\"related-products\">\';

echo \'<h3>\' . __(\'Related Products\') . \'</h3>\';

echo \'<ul>\';

while($relatedPosts->have_posts()){

$relatedPosts->the_post();

?>

<li>

<a href=\"<?php the_permalink(); ?>\"><?php the_post_thumbnail(\'product_thumb\'); ?></a>

<a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a>

</li>

<?php

}

echo \'</ul></div>\';

}else{

//no posts found

}

//restore original post data

wp_reset_postdata();

?>

标签:

提交需求或反馈

Demand feedback