douhui3305 2015-09-17 15:47
浏览 27
已采纳

在缩略图短代码中添加帖子ID请求

I use the following script to create a thumbnail shortcode, but this will only work at a loop or inside the post.

/* Thumb Shortcode */
function my_img() {
if (has_post_thumbnail() ) {
    $image_id = get_post_thumbnail_id();  
    $image_url = wp_get_attachment_image_src($image_id,'medium');  
    $image_url = $image_url[0]; 
    $result = '<img src="'.$image_url.'" class="my_img" />';
    return $result;
}
return;
}
add_shortcode ('my_img', 'my_img');

Is there any simple way to modify it, so that I can use it everywhere with a post ID?

Like this:

<?php echo do_shortcode('[my_img post="100"]'); ?>
  • 写回答

1条回答 默认 最新

  • dongqixian8474 2015-09-17 15:55
    关注

    This function will use shortcode_atts to get the post shortcode attribute if it exist, if not it will use the thumb from the loop:

    function my_img_func($atts) {
        $atts = shortcode_atts(array(
            'post' => null
        ), $atts, 'my_img');
        if($atts['post'] != null) {
            if (has_post_thumbnail((int) $atts['post']) ) {
                $image_id = get_post_thumbnail_id((int) $atts['post']);  
                $image_url = wp_get_attachment_image_src($image_id,'medium');  
                $image_url = $image_url[0]; 
                $result = '<img src="'.$image_url.'" class="my_img" />';
                return $result;
            }
        } else {
            if (has_post_thumbnail() ) {
                $image_id = get_post_thumbnail_id();  
                $image_url = wp_get_attachment_image_src($image_id,'medium');  
                $image_url = $image_url[0]; 
                $result = '<img src="'.$image_url.'" class="my_img" />';
                return $result;
            }
        }
        return '';
    }
    add_shortcode ('my_img', 'my_img_func');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型