显示相关帖子的图片

时间:2019-01-29 作者:R.M. Reza

如何显示相关帖子缩略图?这是我使用的代码:

function related_posts_shortcode( $atts ) {
extract(shortcode_atts(array(
    \'limit\' => \'3\',
), $atts));

global $wpdb, $post, $table_prefix;

if ($post->ID) {
    $retval = \'<div class="related-posts-inline"><p class="related-title-inline">BACA JUGA</p><ul class="related-list-inline">\';
    // Get tags
    $tags = wp_get_post_tags($post->ID);
    $tagsarray = array();
    foreach ($tags as $tag) {
        $tagsarray[] = $tag->term_id;
    }
    $tagslist = implode(\',\', $tagsarray);

    // Do the query
    $q = "SELECT p.*, count(tr.object_id) as count
        FROM $wpdb->term_taxonomy AS tt, $wpdb->term_relationships AS tr, $wpdb->posts AS p WHERE tt.taxonomy =\'post_tag\' AND tt.term_taxonomy_id = tr.term_taxonomy_id AND tr.object_id  = p.ID AND tt.term_id IN ($tagslist) AND p.ID != $post->ID
            AND p.post_status = \'publish\'
            AND p.post_date_gmt < NOW()
        GROUP BY tr.object_id
        ORDER BY count DESC, p.post_date_gmt DESC
        LIMIT $limit;";

    $related = $wpdb->get_results($q);
    if ( $related ) {
        foreach($related as $r) {
            $retval .= \'
<li><a class="link-related" href="\'.get_permalink($r->ID).\'" title="\'.wptexturize($r->post_title).\'">\'.wptexturize($r->post_title).\'</a></li>\';
        }
    } else {
        $retval .= \'
<li>No related posts found</li>\';
    }
    $retval .= \'</ul></div>\';
    return $retval;
}
return;}
add_shortcode(\'related_posts\', \'related_posts_shortcode\');

1 个回复
SO网友:Chinmoy Kumar Paul

我正在通过获取帖子ID的get\\u post\\u thumbnail\\u ID函数获取附件ID。获取该帖子的附件ID后,我将此附件ID传递给wp_get_attachment_image_src 函数并获取图像详细信息。

所以我这样重写你的foreach循环

foreach($related as $r) {
    $thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id($r->ID), \'thumbnail\', true );
    $img= \'\';

    if( is_array( $thumbnail ) ) {
        $img = sprintf(\'<img src="%s" width="%s" height="%s" alt="%s"> \', $thumbnail[0], $thumbnail[1], $thumbnail[2], $r->post_title);
    }

    $retval .= \'<li><a class="link-related" href="\'.get_permalink($r->ID).\'" title="\'.wptexturize($r->post_title).\'">\'. $img . wptexturize($r->post_title).\'</a></li>\';
}

相关推荐

get_posts custom field

这是一个愚蠢的问题,但我找不到合适的方式问谷歌。所以,如果这是一个重复的问题,很抱歉。我提供了一个带有复选框的自定义字段,用户可以检查是否希望此特定帖子进入主页。因此,在我的主页上,我呼吁所有已激活选中的帖子。我正在为自定义帖子类型CV创建自定义字段:function add_custom_post_meta_box() { add_meta_box( \'custom_post_meta_box\', // $id \'Campos Per