Front end post or photo or both

I need a help in correcting my code that can front end post or attach image or post&attach image 😉

Now I can send a ‘post’ and ‘post with photo’ but can’t send just a photo, How can I do that? who can help in this please.

Here is the code

<?php
if ('POST' == $_SERVER['REQUEST_METHOD'] && !empty($_POST['action']) && $_POST['action'] == 'post') {

// Do some minor form validation to make sure there is content

if ($_POST['post_content'] != '') {
    $post_content = $_POST['post_content'];

}  else {

    wp_redirect(get_bloginfo('url') . '/');

    exit ;
}

check_admin_referer('new-post');

$user_id = $current_user -> user_id;
$post_content = $_POST['post_content'];
$char_limit = 40;
$post_title = strip_tags($post_content);
if (strlen($post_title) > $char_limit) {
    $post_title = substr($post_title, 0, $char_limit) . ' ... ';
}
$tags = $_POST['post_tags'];

//Cas as array
$terms = isset($_POST['category']) ? (array)$_POST['category'] : array();

//Cast array values as integers if $_POST['offer'] contains IDs
$terms = array_map('intval', $terms);

$post_id = wp_insert_post(array('post_author' => $user_id, 'post_title' => $post_title, 'post_content' => $post_content, 'post_category' => array($_POST['cat']), // Usable for custom taxonomies too
'tags_input' => array($tags), 'post_type' => $_POST['post_type'], // Use a custom post type if you want to,
'post_status' => 'publish', ));

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');
}

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

}
if ($attach_id > 0) {
    //and if you want to set that image as Post  then use:
    update_post_meta($post_id, '_thumbnail_id', $attach_id);
    echo "uploaded the new Thumbnail";

}

wp_redirect(get_bloginfo('url') . '/');

exit ;
}
?>

And my html post form is

<form id="new_post" name="new_post" method="post" enctype="multipart/form-data" action="<?php bloginfo('url'); ?>" style="width:95%; margin:auto;">
<input type="hidden" name="action" value="post" >
<?php wp_nonce_field('new-post'); ?>
<div>
    <input type="hidden" name="post_type" id="post_type"/>
    <?php   wp_editor('', 'post_content', $settings = array('tinymce' => false, 'wpautop' => true, 'teeny' => true, 'media_buttons' => false, 'quicktags' => false, 'strip_tags' => false, 'textarea_name' => 'post_content',; ?>
</div>
<input type="file" name="attachment" id="attachment" style="display: none;" >

Answer

I’ve made a similar form before, and it works whether it has a post or not. This form does not use wp_editor, but you can just modify the code to suit your need.

add_action('wp_ajax_add_story', 'process_story_entry');

function process_story_entry() {
global $current_user;
if ( empty($_POST) || !wp_verify_nonce($_POST[$current_user->user_login],'add_story') ) {
    echo 'You targeted the right function, but sorry, your nonce did not verify.';
    die();
} else {

    // validate data
    $story_title = $_POST['story-title'];
    $story_detail = $_POST['story-detail'];
    $story_type = $_POST['story-type'];
    $lot_term = $_POST['lot-term'];
    $author = $current_user->ID;
    $return = $_POST['_wp_http_referer'];
    $files = $_FILES['profile-picture'];

    // insert story
    $post = array(
        'comment_status' => 'open',
        'post_author' => $current_user->ID,
        'post_content' => $story_detail,
        'post_status' => 'publish',
        'post_title' => $story_title,
        'post_type' => 'story', 
        'tax_input' => array( 'lot-term' => array( $lot_term ) )
    );      
    $new_story = wp_insert_post( $post, true );

    if($new_story){
        // insert attachment
        $attached_files = attach_uploads($files,$new_story);
        // set as post thumbnail
        if($attached_files){
            set_post_thumbnail( $new_story, $attached_files[0] );   
        }
        // set term
        wp_set_post_terms( $new_story, array($story_type), 'story-type' );
    }

    // redirect to referer page
    wp_redirect($return.'#post-'.$new_story); //dion v12 2
    exit;

    die();
}
}

And the helper functions :

function ajax_response($data,$redirect){
    if(ajax_request()){
        $data_json = json_encode($data);
        echo $data_json;            
    } else {
        wp_redirect( $redirect );
        exit;
    }
}

function rearrange( $arr ){
foreach( $arr as $key => $all ){
    foreach( $all as $i => $val ){
        $new[$i][$key] = $val;    
    }    
}
return $new;
}

function attach_uploads($uploads,$post_id = 0){
$files = rearrange($uploads);
if($files[0]['name']==''){
    return false;   
}
foreach($files as $file){
    $upload_file = wp_handle_upload( $file, array('test_form' => false) );
    $attachment = array(
    'post_mime_type' => $upload_file['type'],
    'post_title' => preg_replace('/\.[^.]+$/', '', basename($upload_file['file'])),
    'post_content' => '',
    'post_status' => 'inherit'
    );
    $attach_id = wp_insert_attachment( $attachment, $upload_file['file'], $post_id );
    $attach_array[] = $attach_id;
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $attach_data = wp_generate_attachment_metadata( $attach_id, $upload_file['file'] );
    wp_update_attachment_metadata( $attach_id, $attach_data );
}
return $attach_array;
}

Hope this help

Attribution
Source : Link , Question Author : Ehab Fawzy , Answer Author : ifdion

Leave a Comment