主机参考_WordPress技巧分享_纯代码使用WordPress短代码添加文章的卡片式链接

Wordpress6年前 (2019)发布 SUYEONE
890 0 0

在撰写博客时,插入相关链接是提升文章质量、增强seo效果以及提供良好用户体验的重要手段。然而,WordPress 4.4版本后的Post Embed功能,虽然尝试以嵌入式卡片的形式展示引用文章,但其单一的样式和不利于SEO的js iframe输出方式,以及加载速度慢的问题,使得这一功能实用性欠佳。

为解决这些问题,我们可以自定义一个更优化的卡片式文章内链功能。以下是一个示例代码,将其添加到你的WordPress主题的functions.php文件中:

“`php
/**
* 卡片式文章内链功能
* https://yourwebsite.com
*/
function custom_Embed_posts( $atts, $content = null ){
extract( shortcode_atts( array(
‘ids’ => ”
),
$atts ) );

global $post;
$content = ”;
$postids = explode(‘,’, $ids);
$inset_posts = get_posts(array(‘post__in’ => $postids));
foreach ($inset_posts as $key => $post) {
setup_postdata( $post );
$content .= ‘

term_id ).'” rel=”noopener noreferrer” >‘. $category[0]->cat_name .’

主机参考_WordPress技巧分享_纯代码使用WordPress短代码添加文章的卡片式链接

‘. get_the_title() . ‘

‘ . wp_trim_words( get_the_excerpt(), 100, ‘…’ ) . ‘

发表日期: ‘ . get_the_date(‘Y/m/d’) . ‘
阅读量: ‘ . get_post_views($post->ID) . ‘
评论数: ‘ . get_comments_number() . ‘
阅读全文

‘;
}
wp_reset_postdata();
return $content;
}
add_shortcode(‘custom_embed_post’, ‘custom_embed_posts’);
“`

同时,创建一个名为`custom-embed-card.CSS`的CSS文件,并将其放入主题的`css`文件夹中,添加以下样式:

“`css
.custom-embed-card {
display: block;
position: relative;
width: 100%;
max-width: 620px;
margin: 30px auto;
border: 1px solid #ddd;
overflow: hidden;
}

/* …其他样式… */
“`

使用此自定义短代码 `[custom_embed_post ids=123,456]` 可在文章中插入卡片式链接,或者通过 `do_shortcode(‘[custom_embed_post ids=123,456]’)` 在其他位置调用。

这个自定义功能不仅提供了美观的卡片样式,而且避免了使用iframe,对SEO更加友好。同时,加载速度和用户体验也得到了改善。

© 版权声明

相关文章

暂无评论

暂无评论...
☺一键登录开启个人书签等功能!