Problema al subir foto en envío de publicaciones

  • Autor Autor quimbox
  • Fecha de inicio Fecha de inicio
quimbox

quimbox

1
Iota
Verificado
Verificación en dos pasos activada
Verificado por Whatsapp
¡Ha verificado su Paypal!
Verificado por Binance
Suscripción a IA
Hola forobetas pues tengo un codigo que consegui de tanto buscar en la web, este codigo permite a los usuarios enviar una publicacion, lo quiero implementar para mi sitio de portadas facebook para que los usuarios puedan publicar portadas, pero al momento de que el usuario envia la publicacion no se sube la foto ni se agrega en el editor de wordpress.

Les agradeceria si me pueden ayudar tengo rato tratando de solucionarlo y no puedo, lo unico que logre fue que la descripcion y los tags que colocan al enviar el post, se agreguen al All In One Seo.

Aqui el codigo
PHP:
<?php
/*
Template Name: Publicar Portada
*/
?>
<?php
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) &&  $_POST['action'] == "new_post") {

	// Do some minor form validation to make sure there is content
	if (isset($_POST['submit'])) {
    		$error = "";

    	if (!empty($_POST['title'])) {
    		$title = $_POST['title'];
   	 } else {
   	 	$error .= "Por Favor Añada Un Titulo<br />";
   	}

    	if (!empty($_POST['description'])) {
    		$description = $_POST['description'];
   	 } else {
   		$error .= "Agrega una descripcion<br />";
   	}

	    if (!empty($_POST['post_tags'])) {
    		$post_tags = $_POST['post_tags'];
   	 } else {
   	 	$error .= "Agrega algunas palabras claves<br />";
   	}

		//if (!empty($_POST['winerating'])) {
    		//$post_tags = $_POST['winerating'];
   	 //} else {
   	 	//$error .= "Please add some keywords<br />";
  // 	}
		// IMAGE VALIDATION - CHECK IF THERE IS AN IMAGE AND THAT ITS THE RIGHT FILE TYPE AND RIGHT SIZE
		if ($_FILES) {
			foreach ($_FILES as $file => $array) {
				//Check if the $_FILES is set and if the size is > 0 (if =0 it's empty)

				if(isset($_FILES[$file]) && ($_FILES[$file]['size'] > 0)) {

					$tmpName = $_FILES[$file]['tmp_name'];
					list($width, $height, $type, $attr) = getimagesize($tmpName);

				if($width!=850 || $height!=315)
				{
					$error .= "La imagen es muy pequeña<br />";
					unlink($_FILES[$file]['tmp_name']); 
				}

				// Get the type of the uploaded file. This is returned as "type/extension"
                $arr_file_type = wp_check_filetype(basename($_FILES[$file]['name']));
                $uploaded_file_type = $arr_file_type['type'];

                 // Set an array containing a list of acceptable formats
                $allowed_file_types = array('image/jpg','image/jpeg','image/gif','image/png');

                 // If the uploaded file is the right format
                if(in_array($uploaded_file_type, $allowed_file_types)) {

				} else { // wrong file type
   	 			$error .= "Por favor usa una imagen en formato JPG, GIF, or PNG file<br />";
                   	 }

				} else {
				$error .= "Por favor agregue una imagen<br />";
				}
			} // end for each
		} // end if

		$tags = $_POST['post_tags'];
		//$winerating = $_POST['winerating'];

		// ADD THE FORM INPUT TO $new_post ARRAY
		if (empty($error)) {
			$new_post = array(
			'post_title'	=>	$title,
			'post_content'	=>	$description,
			'post_category'	=>	array($_POST['cat']),  // Usable for custom taxonomies too
			'tags_input'	=>	array($tags),
			'post_status'	=>	'pending',           // Choose: publish, preview, future, draft, etc.
			'post_type'	=>	'post',  //'post',page' or use a custom post type if you want to
			//'winerating'	=>	$winerating
		);

		//SAVE THE POST
		$pid = wp_insert_post($new_post);

        //KEEPS OUR COMMA SEPARATED TAGS AS INDIVIDUAL
		wp_set_post_tags($pid, $_POST['post_tags']);

		//REDIRECT TO THE NEW POST ON SAVE
		$link = get_permalink( $pid );
		wp_redirect( $link );

		//ADD OUR CUSTOM FIELDS 
		add_post_meta($pid, '_aioseop_keywords', $tags, true); 
		add_post_meta($pid, '_aioseop_description', $description, true);

			//INSERT OUR MEDIA ATTACHMENTS
			if ($_FILES) {
				foreach ($_FILES as $file => $array) {
				$newupload = insert_attachment($file,$pid);
				// $newupload returns the attachment id of the file that
					// was just uploaded. Do whatever you want with that now.
				}
			} // END THE IF STATEMENT FOR FILES
		} // END SAVING POST
	} // END VALIDATION
} // END THE IF STATEMENT THAT STARTED THE WHOLE FORM

//POST THE POST YO
do_action('wp_insert_post', 'wp_insert_post');

?>

<?php get_header(); ?>
	
                      <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
					
					<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
					<?php if ( is_front_page() ) { ?>
						<h2 class="entry-title"><?php the_title(); ?></h2>
					<?php } else { ?>
						<h1 class="entry-title"><?php the_title(); ?></h1>
					<?php } ?>

					
					 <?php
						if (!empty($error)) {
							echo '<p class="error"><strong>Su Mensaje No Fue Enviado<br/> Por el siguiente error:</strong><br/>' . $error . '</p>';
						} elseif (!empty($success)) {
							echo '<p class="success">' . $success . '</p>';
						}
					?>
						<?php the_content(); ?>

		<!-- WINE RATING FORM -->

		<div class="wpcf7">
		<form id="new_post" name="new_post" method="post" action="" class="wpcf7-form" enctype="multipart/form-data">
			<!-- post name -->
			<fieldset name="name">
				<label for="title">Nombre la portada:</label>
				<input type="text" id="title" value="" tabindex="5" name="title" />
			</fieldset>

			<!-- post Category -->
			<fieldset class="category">
				<label for="cat">Selecciona categoria:</label>
				<?php wp_dropdown_categories( 'tab_index=10&taxonomy=category&hide_empty=0' ); ?>
			</fieldset>

			<!-- post Content -->
			<fieldset class="content1">
				<label for="description">Descripcion:</label>
				<textarea id="description" tabindex="15" name="description" cols="80" rows="10"></textarea>
			</fieldset>
<!-- images -->
			<fieldset class="images">
				<label for="bottle_front">Seleccionar Imagen</label>
				<input type="file" name="bottle_front" id="bottle_front" tabindex="25" />
			</fieldset>
<!-- post tags -->
			<fieldset class="tags">
				<label for="post_tags">Palabras clave (separada por coma):</label>
				<input type="text" value="" tabindex="35" name="post_tags" id="post_tags" />
			</fieldset>

			<div align="center">
            <fieldset class="submit">
				<input type="submit" value="Post Review" tabindex="40" id="submit" name="submit" />
			</fieldset>

			<input type="hidden" name="action" value="new_post" /></div>
			<?php wp_nonce_field( 'new-post' ); ?>
		</form>
		 <!-- END WPCF7 -->
	<!-- END OF FORM -->
	<?php endwhile; // end of the loop. ?>
<?php get_footer(); ?>
 
Pues creo que no subes la imagen por eso no lo hace 😀, deberia de quedar con algo como:

PHP:
if ( (move_uploaded_file($tmpName, $dir)) ) {
	echo "Ya está hecho! El archivo se ha guardado como: " . $dir;
} else {
	echo "Error: ¡Ha ocurrido un problema durante la subida!";
}

siendo:
PHP:
$filename = basename($_FILES['$file']['name']);
$dir = dirname(__FILE__) . '/images/' . $filename;

Creo que seria dentro de:

PHP:
if(in_array($uploaded_file_type, $allowed_file_types)) {

}
 
Atrás
Arriba