WordPress 通過簡碼調用附加到文章的最後一張圖片

WordPress的簡碼是一個非常簡單易用的功能,之前我們已經分享瞭 WordPress Shortcode(簡碼)介紹及使用詳解,今天我們一起來看看,WordPress 如何通過簡碼調用附加到文章的最後一張圖片。方法很簡單,隻需要在當前主題的 functions.php 添加下面的代碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
 * 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

發佈留言