I have a wordpress website. There is a category page with a form on it to sort / filter the posts.
I have tried using $_SERVER['PHP_SELF'] as the form action as i need to get the contents of the form to display the posts but when I do it redirects to the index page.
Is there a reason for this? Or a better way to submit a form within wordpress.
Thanks
The reason for this is that Wordpress runs (almost) everything through the index.php page and then handles which page to display via it's routing logic. You might try doing var_dump($_SERVER);
to see which value you want but it's probably $_SERVER['REQUEST_URI']
.
I think what you use redirects to the index because WordPress uses nice URLs.
You can use the function below to "retrieve" the full URL of the current page:
function selfURL()
{
$ret = substr( strtolower($_SERVER['SERVER_PROTOCOL']), 0, strpos( strtolower($_SERVER['SERVER_PROTOCOL']), "/") ); // Add protocol (like HTTP)
$ret .= ( empty($_SERVER['HTTPS']) ? NULL : ( ($_SERVER['HTTPS'] == "on") ? "s" : NULL) ); // Add 's' if protocol is secure HTTPS
$ret .= "://" . $_SERVER['SERVER_NAME']; // Add domain name/IP address
$ret .= ( $_SERVER['SERVER_PORT'] == 80 ? "" : ":".$_SERVER['SERVER_PORT'] ); // Add port directive if port is not 80 (default www port)
$ret .= $_SERVER['REQUEST_URI']; // Add the rest of the URL
return $ret; // Return the value
}
Obviously, you will need to use <form method="GET" action="<?php echo selfURL(); ?>">
to dynamically set the action
of the form.
You are doing wrong thing in html action.
See the thing is that when you use get as form method the previous values disappear from the url.
So to preserve previous values you need to set hidden input for each of the value present in the query string.
See this example of getting those values.
<?php $exclude_values = array('to_date','from_date');
foreach($_GET as $key => $value){
if(!in_array($key,$exclude_values)){?>
<input type="hidden" name="<?php echo $key;?>" value="<?php echo $value;?>"/>
<?php }
}
?>
I m also working on wordpress themes lately.
So chill this answer is perfectly correct as i had undergone this problem a long time ago.
Beware: add those keys in $exclude_values
which are present in the form fields already and those which you donot want after form submission.
And one more thing use the selfURL
function for action field
You could use the the_permalink() wordpress function that will echo the permalink of the current page.