WordPress 通过短代码在文章或评论中显示站内指定文章内容

来自:互联网
时间:2019-01-07
阅读:

WordPress通过短代码在文章或评论中显示站内指定文章内容 wordpress

如果你认真写博客的话肯定会有在文章内引用你站内其他文章的时候,这个时候我们一般都是直接用一个 a 标签来搞定。在 WordPress 4.4 版本新增 Post Embed 功能,可以比较具体的展示链接的信息,可以在任意 WordPress 站点用嵌入的方式插入 WordPress 博客内的文章然后自动的转换成相应的内链块。当然了,前提是嵌入博客主题都支持 Post Embed 功能并且没有禁用掉。虽然这样已经解决了问题,但是我们可以有更好的方案~

因为要调用的是站内文章,如果我们使用get_posts的话可以很好的调用文章的元信息,包括浏览量,缩略图之类的,甚至文章摘要(如果你有的话)。再加上可以自定义样式,这个内链看上去可要比普通的 A 标签高大上多了。

我们可以用短代码的方式添加文章 ID 来直接调用文章,非常方便,下面给出实现方法。

/**
* WordPress通过短代码在文章或评论中显示站内指定文章内容
* https://www.ilxtx.com/insert-post-through-post-id.html
* Modified: 2018-10-22 13:31:49 支持文章数超过5,支持按id填写顺序排列文章
*/
function lxtx_fa_insert_posts( $atts, $content = null ){
    extract( shortcode_atts( array(
        'ids' => ''
    ),
        $atts ) );
    global $post;
    $content = '';
    $postids =  explode(',', $ids);
    $inset_posts = get_posts( array(
            'post__in' => $postids,
            'numberposts' => count($postids),
            'orderby' => 'post__in',
        ) );
    foreach ($inset_posts as $key => $post) {
        setup_postdata( $post );
        $content .=  '<div class="card-today-history"><div class="card-thContents"><div class="card-thLine"></div><div class="card-thHeroTitle"><a target="_blank" class="label--thTitle" href="' . get_permalink() . '">' . get_the_title() . '</a><div class="v-floatRight card-thMeta">' . get_comments_number(). '<i class="iconfont icon-comment"></i></div></div></div></div>';
    }
    wp_reset_postdata();
    return $content;
}
add_shortcode('lxtx_fa_insert_post', 'lxtx_fa_insert_posts');

你可以根据你自己的需要来调整代码,也可以自己自定义 CSS 样式,这里就不给出 CSS 代码了。当然也可以参考本站的结构和 css~

至于调用就非常简单了,直接使用短代码[lxtx_fa_insert_post ids=123,245]即可;当然,如果你不是在文章内容中,而是在其他地方想调用,则可使用do_shortcode('[lxtx_fa_insert_post ids=123,245]')来调用。

返回顶部
顶部