最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

custom post types - Broken featured images are uploading from frontend

matteradmin9PV0评论

I have a form at frontend i want to create post from frontend everything works but when i upload featured image , broken featured image is uploading. I saw uploads folder the image exists there but i can't understand why images are breaking while upload , any help will be appreciated thanks

here is my code.

<?php 
add_action( 'wp_ajax_bpem_event_form_response', 'bpem_event_form_response' );
add_action( 'wp_ajax_nopriv_bpem_event_form_response', 'bpem_event_form_response' );

function bpem_event_form_response() {

$title              = sanitize_text_field($_POST['ev_title']); 
$content            = $_POST['ev_desc'];
$image_url        = sanitize_text_field($_POST['ev_image']);
$location         = sanitize_text_field($_POST['ev_location']);
$start_date       = sanitize_text_field($_POST['ev_start_date']);
$start_time       = sanitize_text_field($_POST['ev_start_time']);
$end_date         = sanitize_text_field($_POST['ev_end_date']);
$end_time         = sanitize_text_field($_POST['ev_end_time']);
$ev_organizer     = sanitize_text_field($_POST['ev_organizer']);
$ev_organizer_url = sanitize_text_field($_POST['ev_organizer_url']);
$group              = sanitize_text_field($_POST['ev_group']);


$post_id = wp_insert_post(array (
   'post_type'         => 'bpem_event',
   'post_title'        => $title,
   'post_content'    => $content,
   'post_status'       => 'publish'
));


add_post_meta( $post_id, 'evn_location', $location );
add_post_meta( $post_id, 'evn_startDate', $start_date);
add_post_meta( $post_id, 'evn_startTime', $start_time);
add_post_meta( $post_id, 'evn_endDate', $end_date);
add_post_meta( $post_id, 'evn_endTime', $end_time);
add_post_meta( $post_id, 'evn_organizer', $ev_organizer);
add_post_meta( $post_id, 'evn_organizer_url', $ev_organizer_url);
add_post_meta( $post_id, 'evn_group', $group);
add_post_meta( $post_id, 'evn_group_slug', sanitize_title($group));



// Add Featured Image to Post

$imagebase        = basename( $image_url ); 
$image_name       = $imagebase;
$upload_dir       = wp_upload_dir(); // Set upload folder
$image_data       = file_get_contents($image_url); // Get image data
$unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name ); // Generate unique name
$filename         = basename( $unique_file_name ); // Create image file name

// Check folder permission and define file location
if( wp_mkdir_p( $upload_dir['path'] ) ) {
    $file = $upload_dir['path'] . '/' . $filename;
} else {
    $file = $upload_dir['basedir'] . '/' . $filename;
}

// Create the image  file on the server
file_put_contents( $file, $image_data );

// Check image file type
$wp_filetype = wp_check_filetype( $filename, null );

// Set attachment data
$attachment = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_title'     => sanitize_file_name( $filename ),
    'post_content'   => '',
    'post_status'    => 'publish'
);

// Create the attachment
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );

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

// Define attachment metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );

// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );

// And finally assign featured image to post
set_post_thumbnail( $post_id, $attach_id );

echo "Success";

    wp_die();
}

Output

I have a form at frontend i want to create post from frontend everything works but when i upload featured image , broken featured image is uploading. I saw uploads folder the image exists there but i can't understand why images are breaking while upload , any help will be appreciated thanks

here is my code.

<?php 
add_action( 'wp_ajax_bpem_event_form_response', 'bpem_event_form_response' );
add_action( 'wp_ajax_nopriv_bpem_event_form_response', 'bpem_event_form_response' );

function bpem_event_form_response() {

$title              = sanitize_text_field($_POST['ev_title']); 
$content            = $_POST['ev_desc'];
$image_url        = sanitize_text_field($_POST['ev_image']);
$location         = sanitize_text_field($_POST['ev_location']);
$start_date       = sanitize_text_field($_POST['ev_start_date']);
$start_time       = sanitize_text_field($_POST['ev_start_time']);
$end_date         = sanitize_text_field($_POST['ev_end_date']);
$end_time         = sanitize_text_field($_POST['ev_end_time']);
$ev_organizer     = sanitize_text_field($_POST['ev_organizer']);
$ev_organizer_url = sanitize_text_field($_POST['ev_organizer_url']);
$group              = sanitize_text_field($_POST['ev_group']);


$post_id = wp_insert_post(array (
   'post_type'         => 'bpem_event',
   'post_title'        => $title,
   'post_content'    => $content,
   'post_status'       => 'publish'
));


add_post_meta( $post_id, 'evn_location', $location );
add_post_meta( $post_id, 'evn_startDate', $start_date);
add_post_meta( $post_id, 'evn_startTime', $start_time);
add_post_meta( $post_id, 'evn_endDate', $end_date);
add_post_meta( $post_id, 'evn_endTime', $end_time);
add_post_meta( $post_id, 'evn_organizer', $ev_organizer);
add_post_meta( $post_id, 'evn_organizer_url', $ev_organizer_url);
add_post_meta( $post_id, 'evn_group', $group);
add_post_meta( $post_id, 'evn_group_slug', sanitize_title($group));



// Add Featured Image to Post

$imagebase        = basename( $image_url ); 
$image_name       = $imagebase;
$upload_dir       = wp_upload_dir(); // Set upload folder
$image_data       = file_get_contents($image_url); // Get image data
$unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name ); // Generate unique name
$filename         = basename( $unique_file_name ); // Create image file name

// Check folder permission and define file location
if( wp_mkdir_p( $upload_dir['path'] ) ) {
    $file = $upload_dir['path'] . '/' . $filename;
} else {
    $file = $upload_dir['basedir'] . '/' . $filename;
}

// Create the image  file on the server
file_put_contents( $file, $image_data );

// Check image file type
$wp_filetype = wp_check_filetype( $filename, null );

// Set attachment data
$attachment = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_title'     => sanitize_file_name( $filename ),
    'post_content'   => '',
    'post_status'    => 'publish'
);

// Create the attachment
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );

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

// Define attachment metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );

// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );

// And finally assign featured image to post
set_post_thumbnail( $post_id, $attach_id );

echo "Success";

    wp_die();
}

Output

Share Improve this question edited Mar 25, 2019 at 21:58 fuxia 107k39 gold badges255 silver badges459 bronze badges asked Mar 25, 2019 at 19:53 Zaheer AbbasZaheer Abbas 968 bronze badges 3
  • You don't have to move the file there yourself, that's probably why it isn't working. WP has functions that'll do all the moving and folder creation for you – Tom J Nowell Commented Mar 25, 2019 at 20:26
  • Also, your code has no checks on the uploaded file, anybody could upload anything, including PHP shells for hacking your website, child pornography, torrents, large files, malware, etc – Tom J Nowell Commented Mar 25, 2019 at 20:27
  • Upload image solution needed. – Zaheer Abbas Commented Mar 25, 2019 at 20:30
Add a comment  | 

1 Answer 1

Reset to default 0

This is the answer of my own question it'll definitely help others to solve same problem.

<?php 

add_action( 'wp_ajax_bpem_event_form_response', 'bpem_event_form_response' );

add_action( 'wp_ajax_nopriv_bpem_event_form_response', 'bpem_event_form_response' );



function bpem_event_form_response() {
$title           = sanitize_text_field($_POST['ev_title']); 
$content         = $_POST['ev_desc'];
$image_url     = sanitize_text_field($_POST['ev_image']);
$location      = sanitize_text_field($_POST['ev_location']);
$start_date    = sanitize_text_field($_POST['ev_start_date']);
$start_time    = sanitize_text_field($_POST['ev_start_time']);
$end_date      = sanitize_text_field($_POST['ev_end_date']);
$end_time      = sanitize_text_field($_POST['ev_end_time']);
$ev_organizer  = sanitize_text_field($_POST['ev_organizer']);
$ev_organizer_url = sanitize_text_field($_POST['ev_organizer_url']);
$group           = sanitize_text_field($_POST['ev_group']);

$post_id = wp_insert_post(array (

'post_type'     => 'bpem_event',
'post_title'    =>   $title,
'post_content'  =>  $content,
'post_status'   => 'publish'

));

add_post_meta( $post_id, 'evn_location', $location );
add_post_meta( $post_id, 'evn_startDate', $start_date);
add_post_meta( $post_id, 'evn_startTime', $start_time);
add_post_meta( $post_id, 'evn_endDate', $end_date);
add_post_meta( $post_id, 'evn_endTime', $end_time);
add_post_meta( $post_id, 'evn_organizer', $ev_organizer);
add_post_meta( $post_id, 'evn_organizer_url', $ev_organizer_url);
add_post_meta( $post_id, 'evn_group', $group);
add_post_meta( $post_id, 'evn_group_slug', sanitize_title($group));
echo "Success 1";
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');

$image = media_sideload_image($image_url, $post_id,"Image",'id');
set_post_thumbnail( $post_id, $image );
echo "Success";

wp_die();
}
Post a comment

comment list (0)

  1. No comments so far