
有一个项目,需要批量导入图片并生成文章:图片名称作为文章的标题,图片还作为特色图片。项目大概几千张图,于是就有了这个插件,批量导入生成。
使用方法:上传插件到wordpress插件目录,开启插件,设置中开启转文章。开启成功后会在后台有红色提示字样。
插件代码,看着改:
<?php /** Plugin Name: 媒体库上传自动生成文章 Plugin URI: https://www.wxnotes.com/ Description: 根据上传的图片生成标题文章,即将上传图片时,将图片名称保存为标题,将图片重命名后设置为特色图片。 Version: 1.0.0 Author: 殷江碧 Author URI: https://www.wxnotes.com/ */ function hello_imgpostinput() { printf( '<p id="imgpostinput" style="color: red;">媒体库上传生成文章插件已开启!请勿进行其他上传图片操作!</p>' ); } if(get_option('imgpostinput')=="1"){//开启功能? add_action( 'admin_notices', 'hello_imgpostinput' ); add_filter('wp_handle_upload_prefilter', 'custom_upload_filter' ); } function custom_upload_filter( $file ){ $info = pathinfo($file['name']); $ext = '.' . $info['extension']; $md5 = md5($file['name']); $file['name'] = $md5.$ext; $post_status = "publish";//设置发文章状态 $user_id = "1";//设置作者id $post_type = "post";//发布文章类型 $post_category = array(1);//分类ID array(8,39) //新建文章 $my_post = array( 'post_title' => $info['filename'], 'post_content' => "", 'post_status' => $post_status, 'post_author' => $user_id, 'post_category' => $post_category, 'post_type' =>$post_type ); //require_once(ABSPATH . 'wp-load.php'); // Insert the post into the database $post_id = wp_insert_post( $my_post );//新建文章并获取文章id //新建文章 $fileid = $post_id + 1; update_post_meta($post_id,'_thumbnail_id',$fileid);//新添加特色图片 return $file; } //增加插件管理菜单 //注册设置 add_action( 'admin_init', 'register_imgpostinput_settings' ); function register_imgpostinput_settings() { //register our settings register_setting( 'imgpostinput-settings-group', 'imgpostinput' ); } if(is_admin()) { /* 利用 admin_menu 钩子,添加菜单 */ add_action('admin_menu', 'add_imgpostinput_page'); } function add_imgpostinput_page() { add_options_page('媒体库上传自动生成文章设置','媒体库上传自动生成文章','manage_options','imgpostinputpage','imgpostinputpage_html'); } function imgpostinputpage_html() { ?> <div class="wrap"> <h1>项目设置</h1> <form method="post" action="options.php"> <?php settings_fields( 'imgpostinput-settings-group' ); ?> <?php do_settings_sections( 'imgpostinput-settings-group' ); ?> <table class="form-table" role="presentation"> <tbody> <tr> <th scope="row"><label for="default_role">开启功能</label></th> <td> <select name="imgpostinput" id="default_role"> <option <? if(get_option('imgpostinput')!="1"){echo "selected=\"selected\"";} ?> value="0">关闭</option> <option <? if(get_option('imgpostinput')=="1"){echo "selected=\"selected\"";} ?> value="1">开启</option> </select> </td> </tr> </tbody></table> <input type="hidden" name="action" value="update" /> <input type="hidden" name="page_options" value="imgpostinputpage" /> <input type="submit" value="保存更改" class="button button-primary" class="button-primary" /> </form> </div> <?php }
发表评论