WordPress:前端帖子提交表单的图像类型

时间:2019-04-23 19:15:01

标签: wordpress frontend submission

有什么方法可以将图像类型默认设置为jpg / jpeg,并且如果用户选择了其他类型,则会向用户显示错误消息?

非常感谢您的帮助。

add_action( 'wp_ajax_nopriv_submit_content', 'my_submission_processor' );
add_action( 'wp_ajax_submit_content', 'my_submission_processor' );

function my_submission_processor() {
    $post_data = array(
        'post_title' => $_POST['post_title'],
        'post_content' => $_POST['post_content'],
        'post_category' => array(324),
        'post_status' => 'publish'
    );

    $post_id = wp_insert_post( $post_data );

    $upload = wp_upload_bits( $_FILES['image']['name'], null, file_get_contents( $_FILES['image']['tmp_name'] ) );

    $wp_filetype = wp_check_filetype( basename( $upload['file'] ), null );

    $wp_upload_dir = wp_upload_dir();

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

    $attach_id = wp_insert_attachment( $attachment, $upload['file'], $post_id );

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

    $attach_data = wp_generate_attachment_metadata( $attach_id, $upload['file'] );
    wp_update_attachment_metadata( $attach_id, $attach_data );

    update_post_meta( $post_id, '_thumbnail_id', $attach_id );

        $new_url = add_query_arg( 'success', 1, get_permalink() );
    wp_redirect( home_url() );

    die();
}

1 个答案:

答案 0 :(得分:0)

也许这是一个重复的问题,这就是您要寻找的。

How to allow <input type="file"> to accept only image files