Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Create PHP variable from form selection WordPress

  • SOLVED

I am trying to use a form selection value to dynamically create a PHP variable. This PHP variable is in turn used to create a new WordPress query.

What is the safest, WordPress-centric way to perform this operation? Will I need to include a submit button with my form or can some nifty Javascript function be used?

Pagination will be required as many results will likely be returned depending on the users selection.

My code looks like this so far:



<?php get_header(); ?>

<div class="clubs-list">

<h1><?php echo post_type_archive_title(); ?> directory</h1>

<form name="clubs" action="" method="post">
<select name="club_type">
<option selected="selected" value="choose">--Classification--</option>
<option value="sports">Sporting</option>
<option value="cultural">Cultural</option>
<option value="educational">Educational</option>
<option value="political">Political</option>
</select>
</form>

<?php $club_type = 'sports'; // PHP variable currently hard-coded - needs to be created from form value ?>

<?php $loop = new WP_Query( array( 'post_type'=>'clubs', 'meta_key'=>'ecpt_club_category', 'meta_value'=>$club_type, 'orderby'=>'title', 'order'=>ASC, 'paged' => get_query_var('paged') ) ); ?>

<?php if ( $loop->have_posts() ) : ?>
<ul>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<li>
<h2><?php the_title(); ?></h2>
<?php echo get_the_post_thumbnail($post->ID, 'tiny'); ?>
<?php the_excerpt(); ?>
<li>
<?php endwhile; ?>
</ul>

<?php wp_pagenavi( array( 'query' => $loop ) ); ?>

<?php wp_reset_postdata(); ?>

<?php endif; ?>

</div>

<?php get_footer(); ?>

Answers (4)

2012-07-13

Arnav Joy answers:

try this

<?php

if($_POST['submit']){
$club_type = $_POST['club_type'];;

}
else{
$club_type = 'sports'; // default value
}

?>

<?php get_header(); ?>



<div class="clubs-list">



<h1><?php echo post_type_archive_title(); ?> directory</h1>



<form name="clubs" action="" method="post" >

<select name="club_type">

<option selected="selected" value="choose">--Classification--</option>

<option value="sports">Sporting</option>

<option value="cultural">Cultural</option>

<option value="educational">Educational</option>

<option value="political">Political</option>

</select>

<input type="submit" name="submit" value="submit" />

</form>







<?php $loop = new WP_Query( array( 'post_type'=>'clubs', 'meta_key'=>'ecpt_club_category', 'meta_value'=>$club_type, 'orderby'=>'title', 'order'=>ASC, 'paged' => get_query_var('paged') ) ); ?>



<?php if ( $loop->have_posts() ) : ?>

<ul>

<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

<li>

<h2><?php the_title(); ?></h2>

<?php echo get_the_post_thumbnail($post->ID, 'tiny'); ?>

<?php the_excerpt(); ?>

<li>

<?php endwhile; ?>

</ul>



<?php wp_pagenavi( array( 'query' => $loop ) ); ?>



<?php wp_reset_postdata(); ?>



<?php endif; ?>



</div>



<?php get_footer(); ?>


designbuildtest comments:

Thanks Arnav


designbuildtest comments:

Hi Arnav. Thanks for the proposed solution. Like Roman and Adam's suggestions, there was a problem when re-submitting the form on a paged URL - no data was returned basically. The approach I finally took is detailed below Adam's answer. Cheers.

2012-07-13

dr_killpatient answers:

Hi!

Try this

<?php if ($_POST['club_type'] !== ""): $club_type = $_POST['club_type']; else $club_type = $club_type = 'sports'; endif; ?>

instead of


<?php $club_type = 'sports'; // PHP variable currently hard-coded - needs to be created from form value ?>

Regards Roman


designbuildtest comments:

Thanks Roman - works well. Please see my response to Adam below re: applying a new filter on a paged URL. Thanks again.

2012-07-13

AdamGold answers:

Try this code (secured by WP nonces):


<?php get_header(); ?>

<?php

if( isset($_POST['wpquestions-form-submit']) && wp_verify_nonce($_POST['wpquestions-form-nonce'],'wpquestions-form-nonce-check') && $_POST['club_type'] != '' ) {

$club_type = $_POST['club_type'];

} else {
$club_type = 'sports';
}

?>



<div class="clubs-list">







<h1><?php echo post_type_archive_title(); ?> directory</h1>







<form id="wpquestions-form" name="clubs" action="" method="post">



<?php wp_nonce_field('wpquestions-form-nonce-check','wpquestions-form-nonce'); ?>

<select name="club_type">



<option selected="selected" value="choose">--Classification--</option>



<option value="sports">Sporting</option>



<option value="cultural">Cultural</option>



<option value="educational">Educational</option>



<option value="political">Political</option>



</select>

<input type="submit" name="wpquestions-form-submit" value="Filter" />

</form>













<?php $loop = new WP_Query( array( 'post_type'=>'clubs', 'meta_key'=>'ecpt_club_category', 'meta_value'=>$club_type, 'orderby'=>'title', 'order'=>ASC, 'paged' => get_query_var('paged') ) ); ?>







<?php if ( $loop->have_posts() ) : ?>



<ul>



<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>



<li>



<h2><?php the_title(); ?></h2>



<?php echo get_the_post_thumbnail($post->ID, 'tiny'); ?>



<?php the_excerpt(); ?>



<li>



<?php endwhile; ?>



</ul>







<?php wp_pagenavi( array( 'query' => $loop ) ); ?>







<?php wp_reset_postdata(); ?>







<?php endif; ?>







</div>







<?php get_footer(); ?>


designbuildtest comments:

Thanks Adam - like your use of nonces. I've amended your code slightly as shown below...

Filtering and pagination work great, but there's a problem when a new filter is applied on a paged URL (i.e.http://localhost/clubs/page/2/).

Re-submiting the form on a paged URL returns no results for any filter (I encountered the same problem with you original code and Roman's code above).

Any suggestions?

Thanks


<?php get_header(); ?>

<?php
if( isset($_POST['wpquestions-form-submit']) && wp_verify_nonce($_POST['wpquestions-form-nonce'],'wpquestions-form-nonce-check') && $_POST['club_type'] != '' ) {
$club_type = $_POST['club_type'];
$loop = new WP_Query( array( 'post_type'=>'clubs', 'meta_key'=>'ecpt_club_category', 'meta_value'=>$club_type, 'orderby'=>'title', 'order'=>ASC, 'paged' => get_query_var('paged') ) );
} else {
$loop = new WP_Query( array( 'post_type'=>'clubs', 'orderby'=>'title', 'order'=>ASC, 'paged' => get_query_var('paged') ) );
}
?>

<div class="clubs-list">

<h1><?php echo post_type_archive_title(); ?> directory</h1>

<form id="wpquestions-form" name="clubs" action="" method="post">
<?php wp_nonce_field('wpquestions-form-nonce-check','wpquestions-form-nonce'); ?>
<select name="club_type">
<option selected="selected" value="choose">--Classification--</option>
<option value="sports">Sporting</option>
<option value="cultural">Cultural</option>
<option value="educational">Educational</option>
<option value="political">Political</option>
</select>
<input type="submit" name="wpquestions-form-submit" value="Filter" />
</form>

<?php if ( $loop->have_posts() ) : ?>

<ul>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<li>
<h2><?php the_title(); ?></h2>
<?php echo get_the_post_thumbnail($post->ID, 'tiny'); ?>
<?php the_excerpt(); ?>
<li>
<?php endwhile; ?>
</ul>

<?php wp_pagenavi( array( 'query' => $loop ) ); ?>

<?php wp_reset_postdata(); ?>

<?php endif; ?>

</div>

<?php get_footer(); ?>


AdamGold comments:

Try:

<?php get_header(); ?>



<?php
wp_reset_query();
if( isset($_POST['wpquestions-form-submit']) && wp_verify_nonce($_POST['wpquestions-form-nonce'],'wpquestions-form-nonce-check') && $_POST['club_type'] != '' ) {

$club_type = $_POST['club_type'];

$loop = new WP_Query( array( 'post_type'=>'clubs', 'meta_key'=>'ecpt_club_category', 'meta_value'=>$club_type, 'orderby'=>'title', 'order'=>ASC, 'paged' => get_query_var('paged') ) );

} else {

$loop = new WP_Query( array( 'post_type'=>'clubs', 'orderby'=>'title', 'order'=>ASC, 'paged' => get_query_var('paged') ) );

}

?>



<div class="clubs-list">



<h1><?php echo post_type_archive_title(); ?> directory</h1>



<form id="wpquestions-form" name="clubs" action="" method="post">

<?php wp_nonce_field('wpquestions-form-nonce-check','wpquestions-form-nonce'); ?>

<select name="club_type">

<option selected="selected" value="choose">--Classification--</option>

<option value="sports">Sporting</option>

<option value="cultural">Cultural</option>

<option value="educational">Educational</option>

<option value="political">Political</option>

</select>

<input type="submit" name="wpquestions-form-submit" value="Filter" />

</form>



<?php if ( $loop->have_posts() ) : ?>



<ul>

<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

<li>

<h2><?php the_title(); ?></h2>

<?php echo get_the_post_thumbnail($post->ID, 'tiny'); ?>

<?php the_excerpt(); ?>

<li>

<?php endwhile; ?>

</ul>



<?php wp_pagenavi( array( 'query' => $loop ) ); ?>



<?php wp_reset_postdata(); ?>



<?php endif; ?>



</div>



<?php get_footer(); ?>


designbuildtest comments:

Thanks for the update Adam. Code still didn't quite work with on paged URL's unfortunately.

In the end I decided to take a different approach and create the variable from a query string. The following code eventually solved my problem:



<?php get_header(); ?>


<?php global $wp_query; ?>

<?php
if (isset($wp_query->query_vars['clubtype'])) {
$club_type = $wp_query->query_vars['clubtype'];
$loop = new WP_Query( array( 'post_type'=>'clubs', 'meta_key'=>'ecpt_club_category', 'meta_value'=>$club_type, 'orderby'=>'title', 'order'=>ASC, 'paged' => get_query_var('paged') ) );
}
else {
$loop = new WP_Query( array( 'post_type'=>'clubs', 'orderby'=>'title', 'order'=>ASC, 'paged' => get_query_var('paged') ) );
}
?>

<div class="clubs-list">


<h1><?php echo post_type_archive_title(); ?> directory</h1>

<form>
<select name="URL" onchange="window.location.href=this.form.URL.options[this.form.URL.selectedIndex].value">
<?php
$clubs = array(
'/clubs/' => 'All clubs',
'/clubs/?clubtype=international' => 'International',
'/clubs/?clubtype=political' => 'Political',
'/clubs/?clubtype=religious' => 'Religious',
'/clubs/?clubtype=special%20causes' => 'Special causes',
'/clubs/?clubtype=sports' => 'Sports',
'/clubs/?clubtype=other' => 'Other'
);
if ( $club_type !='' ) { $selected = '/clubs/?clubtype='.$club_type; } else { $selected = '/clubs/'; }
foreach ($clubs as $code => $label) {
echo '<option value="' . $code . '"';
if ($selected == $code) {
echo ' selected="selected"';
}
echo '>' . $label . '</option>';
}
?>
</select>
</form>


<?php if ( $loop->have_posts() ) : ?>
<ul>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<li>
<h2><?php the_title(); ?></h2>
<?php echo get_the_post_thumbnail($post->ID, 'tiny'); ?>
<?php the_excerpt(); ?>
<li>
<?php endwhile; ?>
</ul>


<?php wp_pagenavi( array( 'query' => $loop ) ); ?>


<?php wp_reset_postdata(); ?>


<?php endif; ?>


</div>


<?php get_footer(); ?>



... and with this snippet added to functions.php



add_filter('query_vars', 'parameter_queryvars' );
function parameter_queryvars( $qvars ) {
$qvars[] = 'clubtype';
return $qvars;
}



Thanks for everyone's suggestions.


designbuildtest comments:

And changed the above code to the following to sanitize the query string value...


if (isset($wp_query->query_vars['clubtype'])) { // Check if a variable is being passed via the query string
$club_qs = $wp_query->query_vars['clubtype']; // Acquire the query string value
$club_type = htmlspecialchars($club_qs, ENT_QUOTES); // Sanitize the query string value
$loop = new WP_Query( array( 'post_type'=>'clubs', 'meta_key'=>'ecpt_club_category', 'meta_value'=>$club_type, 'orderby'=>'title', 'order'=>ASC, 'paged' => get_query_var('paged') ) );
}
else {
$loop = new WP_Query( array( 'post_type'=>'clubs', 'orderby'=>'title', 'order'=>ASC, 'paged' => get_query_var('paged') ) );
}

2012-07-13

Sabby Sam answers:

Hi,
Do the following things:

Paste in header part :

<script type="text/javascript">
function showDetails(str)
{
if (str=="")
{
document.getElementById("output").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("output").innerHTML=xmlhttp.responseText;
}
}
<strong>xmlhttp.open("GET","Getoutput.php?q="+str,true);</strong>
xmlhttp.send();
}
</script>

Note On this content xmlhttp.open("GET","Getoutput.php?q="+str,true); I have made bold for you to undestand kindly write down the full url of your getoutput.php


In the content write this code
<form name="clubs" action="" method="post" onchange="showDetails(this.value)">

<select name="club_type">

<option selected="selected" value="choose">--Classification--</option>

<option value="sports">Sporting</option>

<option value="cultural">Cultural</option>

<option value="educational">Educational</option>

<option value="political">Political</option>

</select>

</form>

<br />
<div id="output">Here details will come.</div>

Step last :
make one fresh file and and paste this code make sure this page name should be Getoutput.php , I have already indicated on the above as a bold.
<?php
$club_type = $_GET["q"]; // PHP variable currently hard-coded - needs to be created from form value ?>



<?php $loop = new WP_Query( array( 'post_type'=>'clubs', 'meta_key'=>'ecpt_club_category', 'meta_value'=>$club_type, 'orderby'=>'title', 'order'=>ASC, 'paged' => get_query_var('paged') ) ); ?>



<?php if ( $loop->have_posts() ) : ?>

<ul>

<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

<li>

<h2><?php the_title(); ?></h2>

<?php echo get_the_post_thumbnail($post->ID, 'tiny'); ?>

<?php the_excerpt(); ?>

<li>

<?php endwhile; ?>

</ul>



<?php wp_pagenavi( array( 'query' => $loop ) ); ?>



<?php wp_reset_postdata(); ?>



<?php endif; ?>

Still if you have problem then you can use this url :
http://www.w3schools.com/php/php_ajax_database.asp

I hope this will help you, still if you don't understand then give me login details I will do this in 10mint.