Redirección del action del formulario a la misma página

14 feb 2013, 14:28:41
Vistas: 40.5K
Votos: 2

Estoy creando mi propio tema. En mi tema tengo una página que muestra entradas personalizadas usando una consulta personalizada. Agregué un formulario a esta página. El formulario contiene 2 cuadros combinados que contienen valores de metadatos de mi entrada personalizada. Quiero que cuando el usuario seleccione valores de estos cuadros combinados y haga clic en enviar, WordPress muestre nuevamente la misma página y agregue el parámetro enviado a mi consulta personalizada (algo así como filtrar una tabla).

El problema es que al hacer clic en enviar, WordPress cae al index.php en lugar de ir a mi página.

Mi declaración del formulario es:

<form action='"<?php echo get_page_link(SHIURIM_PAGE)?> "' method='get'>";

¿Debería poner algo más en el action?

Gracias por adelantado.

Mi código completo de la página:

<?php
/*
Template Name: Shiurim page
*/

require 'search-form.php';
?>

<?php get_header(); 

global $THEME_PATH;
global $IMAGES_PATH;

?>

<link rel="stylesheet" type="text/css" href="<?php _e($THEME_PATH)?>/shiurim.css">

<div id="page-header-pic">
    <img src='<?php _e($IMAGES_PATH)?>/contact-header.jpg' alt="imagen de cabecera" title="Imagen de cabecera">
</div>

<div class="page-title">
    <?php wp_title(); ?>
</div>

<div class="areaBg">
    <div class="page-content-full">
        <div class="panel">
            <div class="panel-title"></div>
            <div class="panel-content">
                <div id="pageContentId">

<?php 
    // Obtiene el parámetro o devuelve el valor por defecto
    function getParam($paramName, $defaultValue) {
        if ($_SERVER['REQUEST_METHOD'] === 'GET') {
            if (!empty($_GET[$paramName])) {
                return $_GET[$paramName];
            }
        }
        else {  // es un post 
            if (!empty($_POST[$paramName])) {
                return $_POST[$paramName];
            }
        }
        return $defaultValue;
    }

    $pageIndex = getParam('paged', 0);
    $searchRav = getParam(SEARCH_RAV, 0);
    $searchSidra = getParam(SEARCH_SIDRA, 0);
    $searchText = getParam(SEARCH_TEXT, "");

    $searchText = trim($searchText);

    $queryArgs = array (
        'post_type' => array( POST_TYPE_SHIUR ),
        'orderby' => 'title',
        'order'    => 'ASC',
        'paged' => $pageIndex
    );

    $paginateSearchArgs = array();
    $metaQuery = array();
    if ($searchRav != 0) {
        $metaQuery[] = array(
            'key' => POST_TYPE_RAV,
            'value' => $searchRav
        );

        $paginateSearchArgs[SEARCH_RAV] = $searchRav;
    }

    if ($searchSidra != 0) {
        $metaQuery[] = array(
            'key' => POST_TYPE_SIDRA,
            'value' => $searchSidra
        );

        $paginateSearchArgs[SEARCH_SIDRA] = $searchSidra;
    }

    if (count($metaQuery) > 0) {
        $queryArgs['meta_query'] = $metaQuery;
    }

    if (! empty($searchText)) {
        $queryArgs['s'] = $searchText;

        $paginateSearchArgs[SEARCH_TEXT] = $searchText;
    }

?>

<div id="shiurimSearchPanel">
    <?php renderSearchFrom($searchRav, $searchSidra, $searchText); ?>
</div>
<div>
<?php 
    //query_posts($queryArgs);
    $shiurim_query = new WP_Query( $queryArgs );
    global $wp_query;
    // Guarda la consulta original en una variable temporal
    $tmp_query = $wp_query;
    // Ahora la limpia completamente
    $wp_query = null;
    // Repobla el global con nuestra consulta personalizada
    $wp_query = $shiurim_query;

    $big = 999999999; // necesita un número entero improbable

    echo paginate_links( array(
        'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
        'format' => '?paged=%#%',
        'current' => max( 1, get_query_var('paged') ),
        'total' => $wp_query->max_num_pages,
        'prev_text' => '&lt;&lt;',
        'next_text' => '&gt;&gt;'
    ) );
?>
</div>

<?php
    $is_first = true;
    if ( $shiurim_query->have_posts() ) : while ( $shiurim_query->have_posts() ) : $shiurim_query->the_post();

?>
            <?php if (!$is_first) { ?>
                    <div class='shiurSeperator'></div>
            <?php } ?>

            <?php
                $is_first = false;

                get_template_part( "content", "shiur-list" );
            ?> 
<?php endwhile; else: ?>
<p><?php _e('No se encontró nada'); ?></p>

<?php 

endif;
// Restaura la consulta original
$wp_query = $tmp_query;
// Sea amable; rebobine
wp_reset_postdata();

 ?>
                </div>
            </div>
        </div>
    </div>

    <div class="clear"></div>
</div>

<?php get_footer(); ?>

search-form.php (Lo estoy usando también en el index.php).

<?php

/**
 *  Panel de búsqueda
 */

function renderSearchFrom($searchRav = array(), $searchSidra = array(), $searchText = "") {
    $rabanimList = getPostArrayResult(POST_TYPE_RAV);
    $sdatorList = getPostArrayResult(POST_TYPE_SIDRA);  

    $html = "<div id='search-panel'>";
    $html .= "  <form action='" . get_page_link(SHIURIM_PAGE). "' method='post'>";
    $html .= "      Por rav";
    $html .= "      <select name='search_rav'>";
    $html .= "          <option value='0'>Todos los ravs</option>";

    foreach ($rabanimList as $rav) {
        $isSelected = ' ';
        if ($rav['id'] == $searchRav) {
            $isSelected = ' selected ';
        }

        $html .= "<option value='" . $rav['id'] . "'" . $isSelected . ">" . $rav['title'] . "</option>";

    } 

    $html .= "</select>";

    $html .= "      Por sidra";
    $html .= "      <select name='search_sidra'>";
    $html .= "          <option value='0'>Todas las sidras</option>";

    foreach ($sdatorList as $sidra) {
        $isSelected = ' ';
        if ($sidra['id'] == $searchSidra) {
            $isSelected = ' selected ';
        }

        $html .= "<option value='" . $sidra['id'] . "'" . $isSelected . ">" . $sidra['title'] . "</option>";
    }

    $html .= "</select>";

    $html .= "      Texto libre";
    $html .= "      <input type='text' name='search_text' class='searchFreeText' value='" . $searchText . "'/>";

    $html .= "      <input type='submit' value='Buscar' />";
    $html .= "  </form>";
    $html .= "</div>";

    echo $html;
}

?>
3
Comentarios

¿Qué contiene SHIURIM_PAGE? ¿Qué devuelve get_page_link(SHIURIM_PAGE)?

Max Yudin Max Yudin
14 feb 2013 14:52:29

¿Cómo se crea esta página? Muéstranos tu código.

Bainternet Bainternet
14 feb 2013 15:04:28

SHIURIM_PAGE es el ID de la página. Voy a agregar el código a las preguntas.

Amos N. Amos N.
14 feb 2013 15:18:12
Todas las respuestas a la pregunta 4
8

Si dejas la acción vacía, el formulario se enviará a la misma página.

Así que simplemente haz esto: <form action='' method='get'>";

14 feb 2013 14:32:36
Comentarios

No funciona. Sigue cayendo en el index.php. El get_page_link(SHIURIM_PAGE) que puse es un enlace directo a la página, pero no ayuda.

Amos N. Amos N.
14 feb 2013 14:37:33

Si pongo method="post" funciona, pero luego tengo problemas con los parámetros de paginación.

Amos N. Amos N.
14 feb 2013 14:38:26

Probablemente estás usando nombres de parámetros que también son utilizados internamente por WordPress. ¡Asegúrate de hacerlos únicos!

jberculo jberculo
14 feb 2013 15:53:58

Mis parámetros son: search_rav, search_sidra y search_text. ¿Son utilizados por Wordpress?

Amos N. Amos N.
14 feb 2013 16:18:10

No lo sé. ¿Seguro que no hay otros? Intenta comprobarlo usando Chrome o firebug para ver cuáles son las variables POST...

jberculo jberculo
14 feb 2013 18:11:24

Encontré el problema y la solución.

Amos N. Amos N.
14 feb 2013 18:20:00

Coloqué la solución y explicación al final de mi pregunta (Stackoverflow no me permitió responder mi propia pregunta).

Amos N. Amos N.
14 feb 2013 18:30:48

Gracias jberculo, tu consejo me guió hacia la solución

Amos N. Amos N.
19 feb 2013 12:10:02
Mostrar los 3 comentarios restantes
0

Encontré el problema y la solución.

El problema:

Al usar:

<form action="<?php echo get_page_link(66) ?>"  method="get"> 

no es lo correcto. En el HTML generado puedo ver:

<form action="http://miSitio/?page_id=66" method="get">

Pero al enviar el formulario, el ?page_id=66 desaparece. Entonces WordPress no sabe redirigir la solicitud a mi plantilla de página.

La solución:

El action debe apuntar a la página de inicio y agregar un campo oculto que contenga el page_id.

<form action="<?php echo home_url ?>"  method="get">
    <input type='hidden' name='page_id' value='66'>

Buena suerte.

19 feb 2013 12:08:16
0

Puedes usar esta forma, es más corta y funciona bien:

<form action="<?php echo get_bloginfo('home').'/?page_id='.get_the_ID();  ? >" method="get" >
28 may 2015 13:26:52
0

Otra forma de enviar un formulario a la misma página es utilizando variables del servidor PHP:

echo "<form name='myForm' action='http://".$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI]."' method='post'>";

Usar la función the_permalink() también podría fallar, porque quizás estás dentro de un bucle y the_permalink() devuelve el enlace permanente del objeto $post que se está procesando actualmente en el bucle.

12 nov 2015 13:10:30