要在WordPress前台使用wp_editor
上传文件并将其附加到文章,您需要进行一些自定义编程。wp_editor
主要用于在后台编辑器中编辑内容,而不是用于前台上传文件。以下是一种可能的方法来实现您的需求:
// 创建一个表单,允许用户在前台上传文件 function custom_upload_form() { ob_start(); ?> <form method="post" enctype="multipart/formdata"> <input type="file" name="custom_upload" /> <input type="submit" name="submit_upload" value="上传文件" /> </form> <?php return ob_get_clean(); } // 处理文件上传并将其附加到文章 function handle_custom_upload() { if (isset($_POST['submit_upload'])) { $file = $_FILES['custom_upload']; $attachment_id = upload_custom_file($file); if ($attachment_id) { // 获取当前文章的ID(您可能需要根据您的情况来获取正确的文章ID) $post_id = get_the_ID(); // 将附件与文章关联 update_post_meta($post_id, '_thumbnail_id', $attachment_id); } } } // 上传文件并返回附件ID function upload_custom_file($file) { require_once ABSPATH . 'wpadmin/includes/file.php'; require_once ABSPATH . 'wpadmin/includes/media.php'; require_once ABSPATH . 'wpadmin/includes/image.php'; // 检查上传目录是否存在,如果不存在则创建它 $upload_dir = wp_upload_dir(); $upload_path = $upload_dir['path']; if (!file_exists($upload_path)) { wp_mkdir_p($upload_path); } // 上传文件 $attachment = wp_handle_upload($file, array('test_form' => false)); if (!isset($attachment['error'])) { // 创建附件 $attachment_data = array( 'post_mime_type' => $attachment['type'], 'post_title' => sanitize_file_name($attachment['file']), 'post_content' => '', 'post_status' => 'inherit' ); $attachment_id = wp_insert_attachment($attachment_data, $attachment['file']); if (!is_wp_error($attachment_id)) { require_once ABSPATH . 'wpadmin/includes/image.php'; $attachment_data = wp_generate_attachment_metadata($attachment_id, $attachment['file']); wp_update_attachment_metadata($attachment_id, $attachment_data); return $attachment_id; } } return false; } // 将自定义上传表单添加到文章内容 function add_custom_upload_form_to_content($content) { if (is_single() && in_the_loop() && is_main_query()) { $upload_form = custom_upload_form(); $content .= $upload_form; } return $content; } add_filter('the_content', 'add_custom_upload_form_to_content'); add_action('init', 'handle_custom_upload');
上述代码包含以下步骤:
- 创建一个前台表单,允许用户上传文件。
- 处理文件上传并将其附加到文章。
- 创建一个自定义的上传文件函数,该函数将文件上传到WordPress媒体库中。
- 使用
the_content
过滤器将上传表单添加到文章内容中。 - 使用
init
挂钩来处理文件上传。
请注意,上述代码中的某些部分可能需要根据您的特定需求进行修改。另外,您还需要确保表单的位置和调用位置与您的主题或插件逻辑相匹配。这只是一个示例,供您参考。