首页 > 解决方案 > 如何在 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' );

标签: phpwordpressshortcodewordpress-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>

推荐阅读