wordpress前端图片怎么上传

2023-12-01 0 650

WordPress教程栏目给大家介绍wordpress前端图片怎么上传。

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前端图片怎么上传的详细内容,更多请关注悠久资源其它相关文章!

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悠久资源 Wordpress教程 wordpress前端图片怎么上传 https://www.u-9.cn/jiaocheng/wordpress-jiaocheng/14987.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务