Añadir campo de carga de imagen a plugin WordPress

  • Autor Autor Felipe
  • Fecha de inicio Fecha de inicio
F

Felipe

Tengo el este plugin para wordpress (Codigo de fuente) y funciona de maravillas, pero quería añadirle un "input" para que el visitante añada una imagen, ojala limitar el tamaño de esa imagen, pero no logro dar con el código.

Insertar CODE, HTML o PHP:
<?php
/*
Plugin Name: Colabora
Plugin URI: http://www.anieto2k.com
Description: Permitimos enviar posts a los usuarios
Author: aNieto2k
Version: 0.1
Author URI: http://www.anieto2k.com
*/


function save_form() {
	global $wpdb;
	if (isset($_POST['contenido']) && isset($_POST['titulo']) && isset($_POST['user']) && get_option('col_userID') != '') {

		// Controlamos la URL
		if (isset($_POST['url']) && $_POST['url'] != '') $user = '<a href="'.apply_filters('pre_comment_author_url', $_POST['url']).'">'.sanitize_user($_POST['user']).'</a>';
		else $user = sanitize_user($_POST['user']);
		
		// Insertamos informacion del colaborador
		$contenido = $_POST['contenido'].'<p class="autor">'.get_option('col_text').': '.$user.'</p>';

		$post_author = get_option('col_userID');
		$post_date = '';
		$post_date_gmt = '';
		$post_content = apply_filters('content_save_pre',   $contenido);
		$post_content_filtered = '';
		$post_title = apply_filters('title_save_pre', $_POST['titulo']);
		$post_excerpt = '';
		$post_status = 'draft';
		$post_type = 'post';
		$comment_status = get_option('default_comment_status');
		$ping_status = get_option('default_ping_status');
		$post_password = '';
		$post_name = '';
		$to_ping = '';
		$pinged = '';
		$post_date = '';
		$post_date_gmt = '';
		$post_parent = '0';
		$menu_order = '0';
		$post_mime_type = '';
		
		// Insertamos el post.		
		$wpdb->query(
				"INSERT IGNORE INTO $wpdb->posts
				(post_author, post_date, post_date_gmt, post_content, post_content_filtered, post_title, post_excerpt,  post_status, post_type, comment_status, ping_status, post_password, post_name, to_ping, pinged, post_modified, post_modified_gmt, post_parent, menu_order, post_mime_type)
				VALUES
				('$post_author', '$post_date', '$post_date_gmt', '$post_content', '$post_content_filtered', '$post_title', '$post_excerpt', '$post_status', '$post_type', '$comment_status', '$ping_status', '$post_password', '$post_name', '$to_ping', '$pinged', '$post_date', '$post_date_gmt', '$post_parent', '$menu_order', '$post_mime_type')");


	if (get_option('col_mail') == '1') {
		//Enviamos un mail a todos los administradores
		$cabeceras  = 'MIME-Version: 1.0' . "\r\n";
		$cabeceras .= 'Content-type: text/html; charset=utf-8' . "\r\n";
		$cabeceras .= 'From:' .get_option('admin_email'). "\r\n";
		//Datos personalizados del mail
		$to = get_option('col_email_to');
		$asunto = get_option('col_asunto');
		$post_ID = $wpdb->insert_id;
		$home = get_option('home');
		$options = '<p>'.__("Opciones").'<a href="'.$home.'/wp-admin/post.php?action=edit&post='.$post_ID.'" >'.__("Ir al POST").'</a>| <a href="'.$home.'?p='.$post_ID.'&preview=true">'.__("Preview").'</a></p>';
		
		mail($to,$asunto.': '.$post_title,$post_content.$options, $cabeceras);
	}
	return '<p class="info">'.get_option('col_OK').'</p>';
			} else {
	return '<p class="info">'.get_option('col_KO').'</p>';
	}
}

function colabora_form($content = '') {

	$msg = '';
	if (isset($_POST['colabora']) && strstr($content,'<!--colabora-->'))
			$msg = save_form();

$salida = $msg.'
<form action="" method="post" id="colabora">
<fieldset>
	<label for="titulo">
	'.__('T&iacute;tulo').': 
	<input name="titulo" id="titulo" type="text" />	
	</label>
</fieldset>
<fieldset>
	<label for="contenido">
	'.__('Contenido').': 
	<textarea name="contenido" id="contenido" cols="30" rows="30"></textarea>
	</label>
</fieldset>
<fieldset>
	<label for="user">
	'.__('Nombre').':
	<input name="user" id="user" type="text" />	
	</label>
	<label for="url">
	'.__('Url').':
	<input name="url" id="url" type="text" />	
	</label>
</fieldset>
<fieldset>
	<p style="text-align:center;"><input type="submit" name="colabora" value="'.__('Enviar').'" /></p>
</fieldset>

</form>';
	return str_replace("<!--colabora-->",$salida,$content);
}

/* PANEL DE ADMINISTRACION */

function colabora_admin_menu(){
	if (get_option('col_text') == '') {
		update_option('col_text', "Colaborador");
		update_option('col_mail', 1);
		update_option('col_email_to', "admin@tusitio.com");
		update_option('col_asunto', "Nueva colaboracion");
		update_option('col_userID', 1);
		update_option('col_OK', "Post enviado, gracias por tu colaboración");
		update_option('col_KO', "Ha ocurrido un error, vuelve a intentarlo.");
	}
	add_options_page('Colabora', 'Colabora', 9, __FILE__, 'colabora_admin') ;
}
add_action('admin_menu', 'colabora_admin_menu'); 

function colabora_admin() {
	if ($_POST['action'] == 'actualiza') {
		update_option('col_text', $_POST['col_text']);
		update_option('col_mail', $_POST['col_mail']);
		update_option('col_email_to', $_POST['col_email_to']);
		update_option('col_asunto', $_POST['col_asunto']);
		update_option('col_userID', $_POST['col_userID']);
		update_option('col_OK', $_POST['col_OK']);
		update_option('col_KO', $_POST['col_KO']);
		
		
	}
$col_text = stripslashes(get_option('col_text'));
$col_mail = (get_option('col_mail') == 1)?'checked="checked"':"";
$col_email_to = stripslashes(get_option('col_email_to'));
$col_asunto = stripslashes(get_option('col_asunto'));
$col_userID = stripslashes(get_option('col_userID'));
$col_OK = stripslashes(get_option('col_OK'));
$col_KO = stripslashes(get_option('col_KO'));

?>
<style type="text/css">
[URL=http://forobeta.com/usertag.php?do=list&action=hash&hash=colabora][URL=http://forobeta.com/usertag.php?do=list&action=hash&hash=colabora]#colabora[/URL] [/URL]  input[type="text"] { width:98%; margin:.6em; }
[URL=http://forobeta.com/usertag.php?do=list&action=hash&hash=colabora][URL=http://forobeta.com/usertag.php?do=list&action=hash&hash=colabora]#colabora[/URL] [/URL]  label { display:block; margin:.5em;}
</style>
<div class="wrap">
  <h2><?php _e('Configuraci&oacute;n del plugin Colabora'); ?> </h2>
  <p>
  	<?php _e('Colabora, es un plugin que te permite abrir las puertas a tus usuarios y permitirles que envien artículos directamente desde tu página. Lo podrán hacer sin tener que estár registrado en el blog. Todos los artículos se almacenarán como borradores del usuario definido como recipiente. En este estado podrás editarlos, revisarlos y posteriormente si crees conveniente publicarlo.<br />
	Para que esto funcione correctamente debes configurar las siguienes opciones antes de empezar a usarlo.');?>
  </p>
  <form id="colabora" name="form1" method="post" action="">
        <input type="hidden" name="action" value="actualiza" />
		<fieldset>
		<label for="col_text">
			<?php _e("Introduce el nombre que aparecerá al lado del colaborador que envie el comentario"); ?>: <input name="col_text" type="text" value="<?=$col_text?>" />
		</label>
			<p style="background-color:#CCCCCC;"><strong>Ejemplo: </strong><br />
			<em>Colaborador</em>: <a href="">Usuario</a>
		</p>
		<label for="col_mail">
		<?php _e("¿Activar envio de mail en cada colaboración?")?> <input name="col_mail" type="checkbox" <?=$col_mail?> value="1" />
		</label>
		<label for="col_email_to">
		<?php _e("Mail al que llegarán las notificaciones de colaboraciones"); ?> <input name="col_email_to" type="text" value="<?=$col_email_to?>" />
		</label>
		<label for="col_asunto">
		<?php _e("Asunto que se añadirá al título enviado por el colaborador");?>	<input name="col_asunto" type="text" value="<?=$col_asunto?>" />
		</label>
			<p style="background-color:#CCCCCC;"><strong>Ejemplo: </strong><br />
			Asunto: <em>Nueva colaboración</em>: Esto es una colaboracion
		</p>
		<label for="col_userID">
		<?php _e("ID del usuario recipiente, este usuario será el que aparecerá como autor de la entrada"); ?>.	<input name="col_userID" type="text" value="<?=$col_userID?>" />
		</label>
		<label for="col_OK">
		<?php _e("Mensaje de que todo ha ido correctamente"); ?>.	<input name="col_OK" type="text" value="<?=$col_OK?>" />
		</label>
		<label for="col_KO">
		<?php _e("Mensaje en caso de ocurrir un error"); ?>.	<input name="col_KO" type="text" value="<?=$col_KO?>" />
		</label>
		</fieldset>
		<input type="submit" value="<?php _e('Enviar');?>" />
	</form>
	<h3><?php _e('¿Como funciona?'); ?></h3>
	<p><?php _e('En cualquier página o post, debes añadir el siguiente código para que este se reemplace por el formulario de envio.'); ?></p>
	<pre style="background-color:#EEE;"><code>&lt;!--colabora--&gt;</code></pre>
	<p><?php _e('Una vez hecho esto aparecerá un formulario que podrás modificar estéticamente desde tu propio CSS. Todos los elementos tienen un ID para que puedas personalizarlo a tu gusto.');?></p>
</div>
<?php
}

add_action('the_content','colabora_form');  
?>

Encontré este codigo para subir un archivo, pero no se si corresponde a wordpress o que... poca idea tengo de progrmación, lo implementé pero no me funcionó, o quizás no lo integré muy bien...

Esto en el Code:
Insertar CODE, HTML o PHP:
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');

$attachment_id = media_handle_upload('file-upload', $post->ID);

Esto en el formulario:
Insertar CODE, HTML o PHP:
<input type="file" name="file-upload" id="file-upload" />

¿Alguien sabe como añadirle ese "input" al plugin?

---------- Post agregado el 14-sep-2013 hora: 19:18 ----------

Bien si alguien lee esto, encontre lo siguiente:

Insertar CODE, HTML o PHP:
<?php 


if(isset($_POST['new_post']) == '1') {
$post_title = $_POST['post_title'];
$post_category = 'fashion';
$post_content = $_POST['post_content'];

$new_post = array(
      'ID' => '',
      'post_author' => $user->ID, 
      'post_category' => array($post_category),
      'post_content' => $post_content,
      'post_title' => $post_title,
      'post_status' => 'draft'
    );

$post_id = wp_insert_post($new_post);


        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');
        }
         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){
    $post = get_post($post_id,'ARRAY_A');
    $image = wp_get_attachment_image_src( $attach_id );
    $image_tag = '<img src="'.$image[0].'" width="'.$image[1].'" height="'.$image[2].'" />';

    //add image above the content
    $post['post_content'] = $image_tag . $post['post_content'];

    //add image under the content
    //$post['post_content'] = $post['post_content'] . $image_tag;

    $post_id =  wp_update_post( $post );
}


// This will redirect you to the newly created post
$post = get_post($post_id);
wp_redirect( get_permalink($post_id));
exit();
}

?>      

<script>
contenido_textarea = ""
num_caracteres_permitidos = 200

function valida_longitud(){
   num_caracteres = document.forms[0].post_content.value.length

   if (num_caracteres > num_caracteres_permitidos){
      document.forms[0].post_content.value = contenido_textarea
   }else{
      contenido_textarea = document.forms[0].post_content.value
   }

   if (num_caracteres >= num_caracteres_permitidos){
      document.forms[0].caracteres.style.color="#ff0000";
   }else{
      document.forms[0].caracteres.style.color="#000000";
   }

   cuenta()
}
function cuenta(){
   document.forms[0].caracteres.value=document.forms[0].post_content.value.length
}


</script> 

<form method="post" action="" enctype="multipart/form-data"> 
<input type="text" name="post_title" size="45" id="input-title" value="Titulo"/><br>
Elige la foto:<br><input type="file" name="thumbnail" id="thumbnail"><br>
Escribe una breve descripción:<br><textarea rows="5" name="post_content" cols="66" id="text-desc" onKeyDown="valida_longitud()" onKeyUp="valida_longitud()"></textarea> <br>
Solo tienes 200 caracteres. <input type="text" name=caracteres size=4> <br>
<input type="hidden" name="new_post" value="1"/> <br>
<input class="subput round" type="submit" name="submit" value="Post"/><br>
</form>

Le añadí el contador de caracteres... xDD Ahora quiero saber como limito el tamaño de las imagenes y que tan solo se suban imagenes, o sea .jpg, jpeg, .png, .gif, etc...

Alguien me ayuda?
 
Para agregar un campo de carga de imagen a tu plugin de WordPress, puedes integrar el siguiente código en tu tarea:

En el código del formulario de colaboración, podrías incluir el campo de carga de imagen de la siguiente manera:

```php
<form action="" method="post" enctype="multipart/form-data" id="colabora">
<!-- Resto de tus campos actuales -->
<fieldset>
<label for="imagen">
<?php _e('Imagen')?>:
<input type="file" name="imagen" id="imagen" accept=".jpg, .jpeg, .png, .gif" />
<!-- Limita los tipos de archivos a imágenes y especifica los formatos permitidos -->
</label>
</fieldset>
<!-- Resto del formulario -->
</form>
```

Luego, en la función `save_form` donde manejas el proceso de guardado de la información del colaborador, podrías agregar el código para manejar la subida de la imagen:

```php
if (isset($_FILES['imagen']) && $_FILES['imagen']['error'] === 0) {
$attachment_id = media_handle_upload('imagen', $post_id);
if (is_wp_error($attachment_id)) {
// Si hay un error al subir la imagen, puedes manejarlo aquí
} else {
// La imagen se ha subido correctamente, puedes acceder a la información del adjunto si es necesario
$image_url = wp_get_attachment_url($attachment_id);
}
}
```

Con este código, se añadirá un campo de carga de imagen al formulario de colaboración y se limitará la subida de archivos a imágenes en los formatos .jpg, .jpeg, .png, y .gif. Adicionalmente, se manejará la subida de la imagen y se podrá obtener la URL de la imagen si es necesario para mostrarla posteriormente.

Si necesitas más ayuda o tienes alguna pregunta adicional, ¡no dudes en consultarme!