Skip to main content

Wordpress user frontend post with media without login


Wordpress user frontend post with media without login

create a page userupload.php in your theme to create auser frontend post with media.
and paste this code into it
<?php
/*
 Template Name: user-post
*/
?><?php get_header(); ?>
<?php
if(isset($_POST['postsubmit']))
{
   
  $post_title = $_POST['post_title'];
  $author_name = $_POST['authorname'];
  $post_category = $_POST['cat'];
  $post_content_img = $_POST['post_content'];
 
 $uploadOk=1;
  if( ! empty( $_FILES['photoContent'] ) ) {
  $name = $_FILES["photoContent"]["name"];
$imageFileType = strtolower(end((explode(".", $name)))); # extra () to prevent notice

if ($_FILES["photoContent"]["size"] > 500000) {
    $msgdata = "<h3 style='color:red'>Sorry, your file is too large.</h3>";
    $uploadOk = 0;
}

if($uploadOk!=0) {
if($imageFileType == "jpg" || $imageFileType == "png" || $imageFileType == "jpeg" || $imageFileType == "gif")
{
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');
            }
           
            $new_post = array(
              'post_author' => $author_name,
              'post_category' => array($post_category),
              'post_content' => $post_content_img,
              'post_title' => $post_title,
              'post_status' => 'pending',
              'post_type' => 'post'
            );
           
           
             $post_id = wp_insert_post($new_post);

            echo $post_id;
           
           
             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);
            }




$msgdata = "<h3 style='color:green'>Post Submitted Successfully.</h3>";
}elseif($imageFileType == "mp4")
{
  foreach( $_FILES as $file ) {
    if( is_array( $file ) ) {
      $attachment_id = upload_user_file( $file );
    $imgurl = wp_get_attachment_url( $attachment_id );
    }
  }
$videoembed = "[video width='426' height='320' mp4='".$imgurl."'][/video]";
$post_content = $videoembed." ".$_POST['post_content'];
 $new_post = array(
  'ID' => '',
  'post_author' => $author_name,
  'post_category' => array($post_category),
  'post_content' => $post_content,
  'post_title' => $post_title,
  'post_status' => 'pending',
  'post_type' => 'post'
);


 $post_id = wp_insert_post($new_post);
set_post_thumbnail( $post_id, $attachment_id );
$msgdata = "<h3 style='color:green'>Post Submitted Successfully.</h3>";
}else {
$msgdata = "<h3 style='color:red'>Invalid File Format.</h3>";
}
}
/*
 if ( ! function_exists( 'wp_handle_upload' ) ) {

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

                $uploadedfile = $_FILES['photoContent'];
                $upload_overrides = array( 'test_form' => false );
                $movefile = wp_handle_upload( $uploadedfile, $upload_overrides );


                 if ($movefile)
                  {
                         //$image_url = preg_replace('#^https?://#',"",$movefile["url"]);
                        $upload_dir = wp_upload_dir();
                        $curl_handle=curl_init();
                curl_setopt($curl_handle, CURLOPT_URL,$movefile["url"]);
                curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
                curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Your application name');
                $image_data = curl_exec($curl_handle);
                curl_close($curl_handle);
                        //$image_data = file_get_contents($movefile["url"]);
                        $filename = basename($image_url);
                        if(wp_mkdir_p($upload_dir['path']))
                            $file = $upload_dir['path'] . '/' . $filename;
                        else
                            $file = $upload_dir['basedir'] . '/' . $filename;
                        $fileurl = "/newspaper/wp-content/uploads/2016/04/";   
                        file_put_contents($file, $image_data);

                        $wp_filetype = wp_check_filetype($filename, null );
                        $attachment = array(
                            'post_mime_type' => $wp_filetype['type'],
                            'post_title' => $post_title,
                            'post_content' => sanitize_file_name($filename),
                            'post_category' => array($post_category),
                            'post_status' => 'publish',
                            'post_type' => 'post',
                            'post_author' => $author_name,
                        );

$base = get_bloginfo('url');
 /*
$post_content = $base." ".$_POST['post_content'];
 $new_post = array(
  'ID' => '',
  'post_author' => $author_name,
  'post_category' => array($post_category),
  'post_content' => $post_content,
  'post_title' => $post_title,
  'post_status' => 'publish',
  'post_type' => 'post'
);
*

 $post_id = wp_insert_post($new_post);


   
                        $listing_post_id = $post_id ; //your post id to which you want to attach the video
                        $attach_id = wp_insert_attachment( $attachment, $file, $listing_post_id);

                        $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
                        wp_update_attachment_metadata( $attach_id, $attach_data );



                        /*end file uploader


*/
                      }

}

?>

  <div id="primary">
        <div id="content" role="main">

  <form method="post" action="" enctype="multipart/form-data" name="myform">

     

      <br /> <br />
      <!----------<Post Title>----->
   <div class="msgbox"><?php if(isset($msgdata)) { echo $msgdata; }; ?></div>
   <span style="font-size: 15px;font-weight: bold;position: relative;right: -93px;">Post Title</span><br />
   <input type="text" required="required" name="post_title"  id="input-title" placeholder="Add A Title Here" class="rounded" style="position: relative;right: -86px;">
  <br>
  <!----------</Post Title>----->
  <span style="font-size: 15px;font-weight: bold;position: relative;right: -93px;">Post Content</span><br />
   <input type="text" required="required" name="post_content"  id="input-title" placeholder="Add A Title Here" class="rounded" style="position: relative;right: -86px;">
 
  <br/>
     <!--<post tags>-->

<fieldset class="tags">

    <label for="post_tags">
<span style="font-size: 15px;font-weight: bold;">Author name :-</span></label><br/>

    <input  type="text" class="rounded" placeholder="Add Some Tags To Get Higher  Votes"value="" size="53" tabindex="35" name="post_tags" id="post_tags"  style="position: relative;right: -86px;">

</fieldset>
    <!--</post tags>-->
     </br>
   <!-- <post Category> -->

<fieldset class="category">

    <label for="cat">
    <span style="font-size: 15px;font-weight: bold;">Select Your Post Category</span></h4></label><div style="position:  relative;right: -85px;"><?php wp_dropdown_categories( 'tab_index=10&taxonomy=category&hide_empty=0' ); ?></div>


  </fieldset>
<!-- </post Category> -->

<label for="ug_photo">Your Video Files
<input type="file" value="" name="photoContent" id="ug_photo" class=""></label>

     <input type="hidden" name="new_post" value="1" /> <br>
    <div style="Float:right;"><input class="submitbutton" type="submit" name="postsubmit" value="Add"  /><br><br></div>
      </form>

      </div></div>
   <!--// New Post Form -->
  <div style="display:inline-block;margin-top:-72px;"></div>
     <div style="position:relative"><?php get_footer(); ?>




AND PASTE THIS CODE INTO YOUR THEME functions.php

function upload_user_file( $file = array() ) {
    require_once( ABSPATH . 'wp-admin/includes/admin.php' );
      $file_return = wp_handle_upload( $file, array('test_form' => false ) );
      if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
          return false;
      } else {
          $filename = $file_return['file'];
          $attachment = array(
              'post_mime_type' => $file_return['type'],
              'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
              'post_content' => '',
              'post_status' => 'inherit',
              'guid' => $file_return['url']
          );
          $attachment_id = wp_insert_attachment( $attachment, $file_return['url'] );
          require_once(ABSPATH . 'wp-admin/includes/image.php');
          $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
          wp_update_attachment_metadata( $attachment_id, $attachment_data );
          if( 0 < intval( $attachment_id ) ) {
              return $attachment_id;
          }
      }
      return false;
}

Comments

Post a Comment

Popular posts from this blog

Run and compile sass scss file to css using node

  Today we learn how to use scss and generate css using node  or Run and compile sass scss file to css using node   So please follow simple  steps :-   Today we will create a project that can read scss file and generates css with it  Note: Make sure you have installed node in your system. If you want to help to install node js based on your system then check our other tutorial or check node js official website. Now create a blank folder and open  terminal(linux) or cmd(windows) and navigate to your current project folder by using cd command Now run below command npm init after enter it will ask you some package info that you can fill according to you or just keep enter until it finished. The above command will generate package.json file Now  we will install npm module that will convert our scss to css Run below command: npm install node-sass So we have installed node-sass package . Now open package.json file in your...

How to retrieve Facebook Likes, share , comment Counts

function facebook_count($url){     // Query in FQL     $fql  = "SELECT share_count, like_count, comment_count ";     $fql .= " FROM link_stat WHERE url = '$url'";     $fqlURL = "https://api.facebook.com/method/fql.query?format=json&query=" . urlencode($fql);     // Facebook Response is in JSON     $response = file_get_contents($fqlURL);     return json_decode($response); } $fb = facebook_count('https://www.facebook.com/BahutHoGyiPadhai'); // facebook share count echo $fb[0]->share_count;  echo "like"; // facebook like count echo $fb[0]->like_count ; echo "comment"; // facebook comment count echo $fb[0]->comment_count;  ?>

Solution-windows 'expo' is not recognized as an internal or external command

Solution for expo is not recognized as an internal or external command,operable program or batch file in Windows 10 Sometimes expo will not work globally mostly in windows 10, If you are facing same issue then follow the below Steps 1) Click on windows button and search for  " Environment variables"  and click on "Edit the system environment variables" 2) Now you will see a popup like below screen. Then you need to click on Environment Variables. (Please see highlight part in below image)     3)Then click on new button that i have highlighted in below image 4. Then a popup will open and you need to fill details like below mentioned Variable Name :Path Variable Value: %USERPROFILE%\AppData\Roaming\npm Here we are creating a new path variable and passing location of npm.   Now Click on OK and close all the terminal windows and open new CMD or terminal and type Expo . Great now you can access expo from any...