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 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理