温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

wordpress前端图片如何上传

发布时间:2021-06-28 10:59:10 来源:亿速云 阅读:252 作者:小新 栏目:建站服务器

这篇文章主要介绍wordpress前端图片如何上传,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

最近研究个项目需要在wordpress前端上传用户头像,在网上查了些资料!解决了这个问题!
1:首先就是在需要的地方添加文件上传框了

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" id="file" name="files[]" multiple="multiple" accept="image/*" />
  <input type="submit" name="submit" value="Upload!" />
</form>

2: 对图片进行处理

$post=get_post(13);//测试用

if ( $_FILES ) {

    $files = $_FILES['files'];
     $count= count($files['name']);

    foreach ($files['name'] as $key => $value) {
        if ($files['name'][$key]) {
            $file = array(
                'name'     => $files['name'][$key],
                'type'     => $files['type'][$key],
                'tmp_name' => $files['tmp_name'][$key],
                'error'    => $files['error'][$key],
                'size'     => $files['size'][$key]
            );

            $_FILES = array("files" => $file);

            foreach ($_FILES as $file => $array) {

                $newupload = insert_attachment($file,$post->ID);//此方法将文章附加到ID为13的文章中。如果不想插入到文章可以为空""
} } } }

3:在functions.php文件添加功能函数

insert_attachment该函数的第二个参数如果为空将不附加到文章中图片。
function insert_attachment($file_handler,$post_id,$setthumb='false') {
 global $wpdb;
  // check to make sure its a successful upload
  if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();

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

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


$image_url = wp_get_attachment_image_src(  $attach_id,'full' ); 
if ($setthumb){ 

  $wpdb->insert(
  $wpdb->prefix . 'postmeta', array(
                'post_id' => $post_id,
                'meta_key' => 'wpcf-vi-img',
                'meta_value' => $image_url[0] ));



  }
  return $attach_id;
}

4:引用方法

$image_url = wp_get_attachment_image_src(  $attach_id,'full' );//由于页面刷新的问题直接在页面使用这个方法是不生效的!需要在函数中构造此方法的功能。

//循环文章中的特征图片的方法,如果将图片附加到文章中使用这个方法可以批量输出!
$imagess=get_post_meta(13,'wpcf-vi-img',false);
foreach($imagess as $images){
 echo  $images;
}

以上是“wordpress前端图片如何上传”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI