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

本人擅长Ai、Fw、Fl、Br、Ae、Pr、Id、Ps等软件的安装与卸载,精通CSS、JavaScript、PHP、ASP、C、C++、C#、Java、Ruby、Perl、Lisp、Python、Objective-C、ActionScript、Pascal等单词的拼写,熟悉Windows、Linux、OS X、Android、iOS、WP8等系统的开关机。

通过下面的方式来联系我们:

电邮:138762189@qq.com

联系QQ:点击这里给我发消息

官方站:www.tadke.com

※ ※ 联系请加我的企鹅号 ※※

※ ※技术支持请微信联系站长 ※※

Copyright © 2023 Tadke.com. 琼ICP备20000547号