php - 如何在 wordpress 中创建自定义的 realted 帖子?
问题描述
在我的 WordPress 网站中,我想向我的博客读者推荐一个特定的帖子。建议的位置在另一个帖子段落之间。例如,我在简码中输入目标帖子的 ID。结果将是该帖子的标题及其缩略图,因此用户可以单击该帖子并查看该帖子。
我得到了这个代码,但它不起作用。它也没有帖子缩略图:
// Add Shortcode
function post_link_shortcode( $atts ) {
// Attributes
$atts = shortcode_atts(
array(
'id' => '',
),
$atts,
'link-to-post'
);
// Return only if has ID attribute
if ( isset( $atts['id'] ) ) {
return '<a href="' . get_permalink( $atts['id'] ) . '">' . get_the_title( $atts['id'] ) . '</a>';
}
}
add_shortcode( 'link-to-post', 'post_link_shortcode' );
解决方案
如果您的简码代码正常工作,您可以通过类似的方式获取帖子的 img。
// Add Shortcode
add_shortcode('link-to-post', 'post_link_shortcode');
function post_link_shortcode($atts)
{
// Attributes
$atts = shortcode_atts(array(
'id' => '',
), $atts);
// Return only if has ID attribute
if (isset($atts['id'])) {
$post = get_post($atts['id']);
ob_start(); ?>
<div class="featured-post">
<a href="<?= get_permalink($post); ?>">
<img src="<?= wp_get_attachment_image_src(get_post_thumbnail_id($post), 'single-post-thumbnail')[0]; ?>" alt="featured image">
</a>
<a href="<?= get_permalink($post); ?>"><?= $post->post_title ?></a>
</div>
<?php
return ob_get_clean();
} else {
return 'No post with that ID found';
}
}
您可以这样做或使用单个链接包装所有内容
<a href="URL"> <!-- CSS display:block will help you -->
img
title
</a>
推荐阅读
- ruby - 在 ruby 中将文件名作为参数传递
- python - 如何处理 Django 中的错误
- python - 如何下载具有授权的文件 - python
- windows - 如何在命令提示符下合并两个 cmd 命令?
- asp.net-core - 在部分视图中传递给表单的模型返回组件(在调用表单之前不为空)在表单发布到控制器时为空
- node.js - 使用 cloudbuild.yaml 部署 Google Cloud 函数(Node JS)时出错
- javascript - 在 jQuery UI 组合框中禁用分隔符
- excel - 在excel中使用SMALL函数,IF函数出现问题
- jquery - 数据表卡在无法读取未定义的属性长度
- javascript - d3 hierarchy ability to average children node values