在wordpress程序中的主题设置文章列表获取的缩略图如果是文章的特色图片的话,那么在编辑文章过程中我们就需要为每篇文章都添加特色图片了。但是这个情况不仅操作麻烦而且在很多的时候效果也不合适,因为很多时候我们只需要在添加图像后把第一张图片设置为特色图片就可以了,所以今天小编就来给大家介绍一下,如何在php空间环境下实现wordpress添加图像后自动把第一张图片设置为特色图片的效果。
首先我们登入的控制面板,点击文件管理按钮,在wordpress程序的主题文件夹里找到functions.php这一个文件,如图1所示:
点击编辑按钮进入文件编辑页面,在代码中的最后添加一段php函数,代码如下:
如图2、图3所示:
代码编辑好了之后点击“提交”按钮,保存文件,这样就可以实现wordpress添加图像后自动把第一张图片设置为特色图片的效果了。
if ( ! function_exists( 'fb_set_featured_image' ) ) { add_action( 'save_post', 'fb_set_featured_image' ); function fb_set_featured_image() { if ( ! isset( $GLOBALS['post']->ID ) ) return NULL; if ( has_post_thumbnail( get_the_ID() ) ) return NULL; $args = array( 'numberposts' => 1, 'order' => 'ASC', // DESC for the last image 'post_mime_type' => 'image', 'post_parent' => get_the_ID(), 'post_status' => NULL, 'post_type' => 'attachment' ); $attached_image = get_children( $args ); if ( $attached_image ) { foreach ( $attached_image as $attachment_id => $attachment ) set_post_thumbnail( get_the_ID(), $attachment_id ); } } }
猜你喜欢