在wordpress上以编程方式上传照片

时间:2013-10-12 10:53:25

标签: php wordpress

我正在尝试将照片上传到wordpress,并使用来自前端的帖子而无需登录。首先,我添加了添加帖子的功能,而无需使用插件从wordpress的前端上传照片。现在我尝试通过在此插件上添加一些代码来添加照片上传功能。但添加代码后,它不上传照片,但它成功发布。我不知道我的错在哪里。请帮我。我的代码如下,

function guestposts_shortcode( $atts ) {
    extract ( shortcode_atts (array(
    'cat' => '1',
    'author' => '1',
    'thanks' => get_bloginfo('home'),
), $atts ) );

return '<form enctype="multipart/form-data" class="guests-post" action="'. plugin_dir_url("guest-posts.php") .'guest-posts/guest-posts-submit.php" method="post">    




<strong>' . __('Post Title:', 'guest-posts') . '</strong><br>
<input type="text" name="title" size="60" required="required" placeholder="' .__('Post title here', 'guest-posts') . '"><br>

 <input type="file" name="upload" id="file"><br>

    <strong>' . __('Story', 'guest-posts') . '</strong>
    '. wp_nonce_field() .'
        <textarea rows="15" cols="72" required="required" name="story" placeholder="' . __('Start writing your post here', 'guest-posts') . '"></textarea><br>
    <strong>' . __('Tags', 'guest-posts') . '</strong><br>
        <input type="text" name="tags" size="60" placeholder="' . __('Comma Separated Tags', 'guest-posts') . '"><br><br>
    <strong>' . __('Your Name', 'guest-posts') . '</strong><br>
        <input type="text" name="author" size="60" required="required" placeholder="' . __('Your name here', 'guest-posts') . '"><br>
    <strong>' . __('Your Email', 'guest-posts') . '</strong><br>
        <input type="email" name="email" size="60" required="required" placeholder="' . __('Your Email Here', 'guest-posts') . '"><br>
    <strong>' . __('Your Website', 'guest-posts') . '</strong><br>
        <input type="text" name="site" size="60" placeholder="' . __('Your Website Here', 'guest-posts') . '"><br><br><br>
    <input type="hidden" value="'. $cat .'" name="category"><input type="hidden" value="'. $author .'" name="authorid">
    <input type="hidden" value="'. $thanks .'" name="thanks">
    <input type="hidden" value="'. str_replace('/wp-content/themes', '', get_theme_root()) .'/wp-blog-header.php" name="rootpath">
    <input type="submit" value="' . __('Submit The Post', 'guest-posts') . '"> <input type="reset" value="' . __('Reset', 'guest-posts') . '"><br>
    </form>
    ';
}
add_shortcode( 'guest-posts', 'guestposts_shortcode' );

此代码处理从上面的代码发送的数据

ob_start();
require_once($_POST["rootpath"]);

        if (!function_exists('wp_generate_attachment_metadata')){
            require_once(ABSPATH . "wp-admin" . '/includes/image.php');
            require_once(ABSPATH . "wp-admin" . '/includes/file.php');
            require_once(ABSPATH . "wp-admin" . '/includes/media.php');
        }

$title = $_POST["title"];
$story = $_POST["story"];
$tags = $_POST["tags"];
$author = $_POST["author"];
$email = $_POST["email"];
$site = $_POST["site"];
$authorid = $_POST["authorid"];
$category = $_POST["category"];
$thankyou = $_POST["thanks"];
$path = $_POST["rootpath"];
$nonce=$_POST["_wpnonce"];
$filename=$_FILES["file"]["name"];
//$file=$_FILES["file"];
//Load WordPress
//require($path);

//Verify the form fields
if (! wp_verify_nonce($nonce) ) die('Security check'); 

$new_post = array(
        'post_title'    => $title,
        'post_content'  => $story,
        'post_category' => $category,  // Usable for custom taxonomies too
        'tags_input'    => $tags,
        'post_status'   => 'publish',           // Choose: publish, preview, future,     draft, etc.
        'post_type' => 'post',  //'post',page' or use a custom post type if you want to
        'post_author' => $authorid //Author ID
);
//save the new post
    $post_id = wp_insert_post( $new_post ); 




if ($_FILES) {

            foreach ($_FILES as $file => $array) {
                if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
                    return "upload error : " . $_FILES[$file]['error'];

               }

  $wp_filetype = wp_check_filetype(basename($file ), null );
  $wp_upload_dir = wp_upload_dir();

 $attachment = array(
     'guid' => $wp_upload_dir['url'] . '/' . basename( $file ), 
     'post_mime_type' => $wp_filetype['type'],
     'post_title' => preg_replace('/\.[^.]+$/', '', basename($file )),
     'post_content' => '',
     'post_status' => 'publish'
  );


          $attach_id = wp_insert_attachment( $attachment, $file, $post_id );
    $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
        wp_update_attachment_metadata( $attach_id,  $attach_data );


            }   
        }
/* Insert Form data into Custom Fields */
add_post_meta($post_id, 'author', $author, true);
add_post_meta($post_id, 'author-email', $email, true);
add_post_meta($post_id, 'author-website', $site, true);

header("Location: $thankyou");

?>

1 个答案:

答案 0 :(得分:0)

使用media_handle_upload功能要好得多。使用以下函数上传文件并返回附件ID ...

function guestposts_handle_attachment( $file_handler, $post_id ) {

    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    require_once( ABSPATH . 'wp-admin/includes/file.php' );
    require_once( ABSPATH . 'wp-admin/includes/media.php' );

    $attachment_id = media_handle_upload( $file_handler, $post_id );

    if( !is_wp_error( $attachment_id ) ) {

        return $attachment_id;

    }

    return false;

}

然后,当您处理表单时,您可以使用此代码执行该功能并使上传的文件成为精选图像......

if( !empty( $_FILES ) ) {

    $attachment_id = guestposts_handle_attachment( 'upload', $post_id );

    if( $attachment_id ) {

        set_post_thumbnail($post_id, $attachment_id);

    }

}

希望有所帮助。

此致