Solución al error de plugin de preguntas

  • Autor Autor Diegotrap
  • Fecha de inicio Fecha de inicio
D

Diegotrap

Hola, estoy desarrollando un post que permite a los usuarios postear preguntas, pero cuando ya se envia la pregunta recibo el siguiente warning:

Warning: Cannot modify header information - headers already sent by (output started at /nfs/c02/h10/mnt/43444/domains/preguntando.org/html/wp-content/themes/money-theme/header.php:2) in /nfs/c02/h10/mnt/43444/domains/preguntando.org/html/wp-includes/pluggable.php on line 866

Lo curioso es que la pregunta me aparece en el panel de Wordpress pendiente de publicación, como se supone que debe hacer el plugin.

Podeis ver un ejemplo del error en cualquiera de los posts de Preguntando - Un blog de preguntas y respuestas... en la sección ¿Tienes alguna pregunta más?, debajo de cada nota.

Estaría muy agradecido a los usuarios de Forobeta que me ayuden a resolver este problema para poder continuar con el plugin.
 
Muchas gracias SoloNegocios, de hecho el plugin utiliza tu código de "Crear una comunidad de Wordpress sin plugins"

Te pego el código:
PHP:
<?php
/*
Plugin Name: Preguntas
Plugin URI: http://preguntando.org
Description: Preguntas for Wordpress.
Version: 0.1
Author: Diego Trapero
Author URI: http://diegotrap.com
License: Mine!
*/

/* Create post type: Question */
add_action( 'init', 'codex_custom_init' );
function codex_custom_init() {
  $labels = array(
    'name' => 'q',
    'singular_name' => 'Pregunta',
    'add_new' => 'Añadir nuevo',
    'add_new_item' => 'Añadir nueva Pregunta',
    'edit_item' => 'Editar pegunta',
    'new_item' => 'Nueva Pregunta',
    'all_items' => 'Todas las Preguntas',
    'view_item' => 'Ver pregunta',
    'search_items' => 'Buscar Preguntas',
    'not_found' =>  'No se encontraron preguntas',
    'not_found_in_trash' => 'No hay preguntas en la Papelera', 
    'parent_item_colon' => '',
    'menu_name' => 'Preguntas'
  );
  $args = array(
    'labels' => $labels,
    'public' => true,
    'publicly_queryable' => true,
    'show_ui' => true, 
    'show_in_menu' => true, 
    'query_var' => true,
    'rewrite' => true,
    'capability_type' => 'post',
    'has_archive' => true, 
    'hierarchical' => false,
    'menu_position' => null,
    'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
  );
  register_post_type('q',$args);
}

//add filter to ensure the text Book, or book, is displayed when user updates a book 
add_filter( 'post_updated_messages', 'codex_book_updated_messages' );
function codex_book_updated_messages( $messages ) {
  global $post, $post_ID;

  $messages['book'] = array(
    0 => '', // Unused. Messages start at index 1.
    1 => sprintf( __('Book updated. <a href="%s">View book</a>'), esc_url( get_permalink($post_ID) ) ),
    2 => __('Custom field updated.'),
    3 => __('Custom field deleted.'),
    4 => __('Book updated.'),
    /* translators: %s: date and time of the revision */
    5 => isset($_GET['revision']) ? sprintf( __('Book restored to revision from %s'), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
    6 => sprintf( __('Book published. <a href="%s">View book</a>'), esc_url( get_permalink($post_ID) ) ),
    7 => __('Book saved.'),
    8 => sprintf( __('Book submitted. <a target="_blank" href="%s">Preview book</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
    9 => sprintf( __('Book scheduled for: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Preview book</a>'),
      // translators: Publish box date format, see http://php.net/date
      date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( get_permalink($post_ID) ) ),
    10 => sprintf( __('Book draft updated. <a target="_blank" href="%s">Preview book</a>'), esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
  );

  return $messages;
}


/* QUESTION FORM 
------------------------------*/

function get_question_form()
{

// Display message sirve para devolver mensajes de error
function display_message( $message = false ) 
{ 
 if( is_wp_error( $message ) ) 
 { 
  echo '<p>' . $message->get_error_message() . '</p>';     
 } 
}

// Post variables
if(isset($_POST['boton1'])) 
{ 
 $articulo_title = $_POST['articulo_title']; 
 $articulo_content = $_POST['articulo_content']; 
 $message = new_question($articulo_title, $articulo_content); 
}
?>
<form action="" method="post" enctype="multipart/form-data"> 
	<?php display_message($message) ?>
		<fieldset>
			<ul>
				<li>
					<label>Titulo</label>
					<input type="text" name="articulo_title" id="articulo_title" size="30" value="<?php echo $_POST['articulo_title']?>" />
				</li>
				<li>
					<label>Tu opinión</label>
					<textarea rows="10" cols="40" name="articulo_content" id="articulo_content"><?php echo $_POST['articulo_content']?></textarea>
				</li>
			</ul>
		</fieldset>
		<fieldset>
			<ul>
			</ul>
		</fieldset>
		<fieldset>
			<ul>
				<li>
					<center><input type="submit" name="boton1" id="publicar" value="Enviar pregunta"/></center>
				</li>
			</ul>
		</fieldset>
	</form>
<?php
}

/* NEW QUESTION 
------------------------------*/
function new_question($question_title, $question_content) 
{ 
 //Strip any tags then may have been put into the array 
 $question_title_stripped = strip_tags($question_title); 
 $question_content_stripped = strip_tags($question_content); 

 // Get the Current User Info 
 $user = wp_get_current_user(); 
     
 global $wpdb; 
 $gather_questions = "SELECT * FROM wp_posts WHERE post_author = '" . $user->ID . "'"; 
 $user_questions = $wpdb->get_results($gather_questions); 

 // Validate the Form Data 
 if (empty($question_title_stripped)) 
 { 
  return new WP_Error('no_title_entered', 'Escribe el Titulo de tu Opinión'); 
 } 
 if (empty($question_content_stripped)) 
 { 
  return new WP_Error('no_content', 'Escribe tu Opinión sobre el Producto que Compraste'); 
 } 
 if (str_word_count($question_content_stripped)<30) 
 { 
  return new WP_Error('content_corto', 'Tu Opinión es muy corta cuéntanos mas del Producto que Compraste, recuerda decirnos cuales fueron las cosas que te gustaron y las que no te gustaron del Producto'); 
 } 

 // Validate - Check to see if user already posted this exact question 
 foreach ($user_questions as $user_question) 
 { 
  if ($user_question->post_author == $user->ID ) 
  { 
   if ($user_question->post_title == $question_title_stripped) 
   { 
    return new WP_Error('duplicate_user_question', 'Ya hay una Opinión con este Titulo, Cambia el Titulo'); 
   } 
   else  
   { 
   }             
  } 
  else 
  { 
  } 
 } 
 $question_author = 7;

 $post = array( 
      'ID' => '', 
      'post_author' => $question_author,  
      'post_category' => array($question_category), 
      'post_content' => $question_content_stripped,  
      'post_title' => $question_title_stripped, 
      'post_status' => 'pending',
      'post_type' => 'q'
    );   

// Insert the Question into the DB 
$question_id = wp_insert_post($post); 
// Get the newly created post info for redirection 
$question = get_post($question_id); 
     
// Redirect to the newly posted Question 
wp_redirect($question->guid); 
}

Luego en el single.php hago una llamada a get_question_form()
 
Reemplaza esta ultima linea:
PHP:
// Redirect to the newly posted Question 
wp_redirect($question->guid);

Por el texto que deseas que aparezca y debería estar solucionado. 😉
 
hola, me ha surgido alguna vez que otra ese tipo de error, y me lo produce por dejar una linea en blanco en el header o function, y en algun que otro archivo, es decir, que el inicio
<?php comienza en la linea 2 en vez de la linea 1, todo es ponerlo en su sitio y todo resuelto, y es curioso ese fallo, porque solo lo da con determinadas funciones y plugin.
Me paso que todo estaba correcto, pero cuando entraba en el administrador, cuando intentaba editar un post, me soltaba un error similar, solo cuando intentaba editar un post, para volverse loco, y el fallo era ese, un espacio en blanco en el function del theme.
 
Muchas gracias, la clave estaba en lo que ha apuntado Skinet.

¿Cómo podría poner un mensaje de que la pregunta ha sido recibida?
 
Pues simplemente pon donde estaba esto:
PHP:
// Redirect to the newly posted Question 
wp_redirect($question->guid);

Por ejemplo:
PHP:
echo "Pregunta guardada correctamente";

Y con eso debería de funcionar sin problemas
 
Atrás
Arriba