WordPress 通过简码调用附加到文章的最后一张图片

时间:2019-08-29   阅读:406

WordPress的简码是一个非常简单易用的功能,之前我们已经分享了 WordPress Shortcode(简码)介绍及使用详解,今天我们一起来看看,WordPress 如何通过简码调用附加到文章的最后一张图片。方法很简单,只需要在当前主题的 functions.php 添加下面的代码:

1
2
3
4
5
/**
 * WordPress 通过简码调用附加到文章的最后一张图片
 * https://www.wpdaxue.com/wordpress-shortcode-display-the-last-image-attached-to-post.html
 */function wpdx_postimage($atts, $content = null) {extract(shortcode_atts(array("size" => 'thumbnail',"float" => 'none'), $atts));$images =& get_children( 'post_type=attachment&post_mime_type=image&post_parent=' . get_the_id() );foreach( $images as $imageID => $imagePost )$fullimage = wp_get_attachment_image($imageID, $size, false);$imagedata = wp_get_attachment_image_src($imageID, $size, false);$width = ($imagedata[1]+2);$height = ($imagedata[2]+2);return '<div class="postimage" style="width: '.$width.'px; height: '.$height.'px; float: '.$float.';">'.$fullimage.'</div>';}add_shortcode("postimage", "wpdx_postimage");

/** * WordPress 通过简码调用附加到文章的最后一张图片 * https://www.wpdaxue.com/wordpress-shortcode-display-the-last-image-attached-to-post.html */ function wpdx_postimage($atts, $content = null) { extract(shortcode_atts(array( "size" => 'thumbnail', "float" => 'none' ), $atts)); $images =& get_children( 'post_type=attachment&post_mime_type=image&post_parent=' . get_the_id() ); foreach( $images as $imageID => $imagePost ) $fullimage = wp_get_attachment_image($imageID, $size, false); $imagedata = wp_get_attachment_image_src($imageID, $size, false); $width = ($imagedata[1]+2); $height = ($imagedata[2]+2); return '<div class="postimage" style="width: '.$width.'px; height: '.$height.'px; float: '.$float.';">'.$fullimage.'</div>'; } add_shortcode("postimage", "wpdx_postimage");

然后我们在文章中使用下面的简码就可以调用文章的最后一张图片啦:

[postimage]

参考资料:wprecipes.com

上一篇:WordPress 站点集成 Google 自定义搜索引擎

下一篇:WordPress 生成文章预览链接给其他用户查看

网友评论