I'm running in circle, i'm trying to run a query from a custom search form and to display the result on a specific custom page.
I've created a custom search page called search-custom.php and i've registered it.
Now I don't understand why when I submit my seachform i'm getting a 404 error.
This is my searchform currently, upon submitting the form, the url path seems right, am I missing something?
<form action="<?php echo esc_url( home_url().'/search-custom' ); ?>" method="get">
<input type="hidden" name="s" value="<?php the_search_query(); ?>">
<input type="hidden" value="qcm" name="post_type">
<button type="submit"><span class="mr-2">Go</button>
</form>
I don't want to redirect it from the function.php file I need this current format. Thanks in advance for your lights.
You do not need to change the action of your form to the name of your template file. Inside of your search-custom.php there is:
<form action="<?php echo esc_url( home_url( '/' ) ); ?>" method="get">
<input type="hidden" name="s" value="<?php the_search_query(); ?>">
<input type="hidden" value="qcm" name="post_type">
<button type="submit"><span class="mr-2">Go</button>
</form>
With this template file having set, you can use it in your page template (the page you want the form to display, or maybe in a sidebar or something) with:
<?php get_template_part( 'search', 'custom' ); ?>
The default wordpress search template will be used to output the results.
If you want to use a different template file for the results, you can put this in the functions.php file of your theme and change the results page (i.e. search-results-custom.php):
add_action('template_include', 'search_custom_template');
function search_custom_template( $template ) {
if ( isset( $_REQUEST['search'] ) && is_search() ) {
$temp = locate_template('search-results-custom.php');
if ( ! empty($temp) ) {
$template = $temp;
}
}
return $template;
}
Multiple search results pages using different forms
If you want to set a value in your form, and using that to get to specific result pages:
Open the search.php file of your theme, make a copy for safety and replace the whole content of the file with the following code:
<?php
if(isset($_GET['post_type'])) {
$type = $_GET['post_type'];
if($type == 'qcm') {
load_template(TEMPLATEPATH . '/search-custom.php');
} elseif($type == 'another') {
load_template(TEMPLATEPATH . '/search-another.php');
}
}
?>
In this code we check what value is set for the field with the name post_type. In your question, you have set the value of qcm. When the field has this value on submit, you will load the search-custom.php. If you have other forms with other values, you can just add an elseif and load another search results template.
If you want to use another hidden input for checking the value, you can simply create one:
<input type="hidden" name="my-hidden-info" value="value-to-check" />
As you see, this way you can edit a value inside of your form and get different search results pages for the specific values. The action of the form is not changed and you will always use the search.php file. You just add other templates, which you are loading inside of this file in the if and elseif. So you get multiple search results pages using different forms.
Related
I am creating a WordPress plugin and I have added a form to the plugin's Settings page. I want to perform a specific operation after the form is submitted and the "Save Changes" button is clicked.
I have tried using the isset() function and other ways, but none of them seem to be working.
Here is the code for my form:
<div class="wrap">
<div id="icon-themes" class="icon32"></div>
<h2>My Settings</h2>
<?php settings_errors();
if (isset($_POST['form_submitted'])) {
echo '<script>alert("Hello World")</script>';
} ?>
<form method="POST" action="options.php">
<?php
settings_fields('my_general_settings');
do_settings_sections('my_general_settings');
?>
<?php submit_button(); ?>
<input type="hidden" name="form_submitted" value="1">
</form>
</div>
What would be the correct way to perform an action after the form is submitted and the "Save Changes" button is clicked? Is there a built-in hook that can be used for this? Or perhaps something like this: isset( $_GET[ 'settings-updated' ] ?
You can try using the "admin_init" hook. This hook is called after WordPress has finished loading but before any headers are sent.
function your_plugin_settings_init() {
// This is checking if your form is submitted
if (isset($_POST['form_submitted'])) {
// perform your specific operation here
echo '<script>alert("Hello World")</script>';
}
}
add_action('admin_init', 'your_plugin_settings_init');
I'm currently trying to add a debug page to my website. This page is simply dedicated to running some of the tasks done by my plugin and outputting some results on the same page.
I currently have a separate page in my Wordpress admin, this page contains a form and button that should be linked to a function that will do various steps and then return a value that must be printed on that page.
Here's the current code for the page and button :
function actu_admin_menu_option()
{
add_menu_page('Scripts', 'Sahar actus plugin', 'manage_options', 'actu-admin-menu', 'actu_scripts_page', '', 200);
}
add_action('admin_menu', 'actu_admin_menu_option');
// HTML page of the plugin
function actu_scripts_page()
{
?>
<div class="wrap">
<h2>Sahar actus plugin</h2>
<form action="<?php echo admin_url('admin-post.php'); ?>" method="post">
<input type="hidden" name="action" value="start_test">
<input class="button button-primary" type="submit" value="Start test">
</form>
</div>
<?php
}
function start_test()
{
return ("test started!");
}
add_action( 'admin_post_start_test', 'start_test' );
What I would like is for example to run the following function when clicking on the button and then outputting the returned value on the page.
function start_test()
{
return("test started!");
}
So when I press the button I want "test started!" to be printed on the page, currently clicking on the button redirects me to /wp-admin/admin-post.php which is a blank page.
I have no idea what is the best course of action to do it, should I make an ajax request on my button to run the function and then get the return value from that ajax call ? Or is there a better way to go about this ?
Thanks for helping me, have a great day
EDIT : Updated code, no errors but output is still not printed to page or console.
function actu_scripts_page()
{
?>
<div class="wrap">
<h2>Sahar actu plugin</h2>
<form action="" method="post">
<?php wp_nonce_field('do_test', '_test_nonce') ?>
<input type="hidden" name="action" value="start_test">
<input class="button button-primary" type="submit" value="Start test">
</form>
</div>
<?php
if (isset($_POST['start_test'])) {
if (isset($_POST['start_test'])) {
if (!wp_verify_nonce($_POST['_test_nonce'], 'do_test')) {
// error in nonce
} else {
start_test();
}
}
}
?>
<?php
}
function start_test()
{
echo("hhhhh");
die(); // tried with and without, no difference
}
add_action('admin_post_start_test', 'start_test');
There are two ways to acheive this, both are fine, it just depends on the user experience you desire. Use the normal http form submission (what you have already), or use ajax. The normal form submission is the easiest method.
Submit the form using the standard method (what you have there), which will reload the page. Important Note it would be better to leave the action attribute blank like action="" if you are submitting the page to itself.
You will also want to add a nonce to the form using wp_nonce_field() and check its value in the submission block with wp_verify_nonce().
So your form would like something like this:
<form action="" method="post">
<?php wp_nonce_field('do_test', '_test_nonce') ?>
<input type="hidden" name="action" value="start_test">
<input class="button button-primary" type="submit" value="Start test">
</form>
Add a php block to check if the form has been submitted and do your script in there, printing any output with php.
function start_test() {
// do things. If successful, return true. Otherwise return false
return true;
}
if( isset($_POST['start_test']) ) {
if( ! wp_verify_nonce( $_POST['_test_nonce'], 'do_test' ) {
// error in nonce
} else {
if( start_test() )
echo '<p>Success!</p>';
else
echo '<p>Failure!</p>';
}
}
There is a redirection happening through /wp-admin/admin-post.php that will return you back to the previous screen.
Your results are being printed on this page, and since it's redirecting, you don't get to see anything.
All you need to do to solve this issue, is add this after your debugging code:
die();
Or
exit();
This will stop the PHP from executing anything after your code. Thus, stopping the page from redirecting. Also, any functions that will run after you function, will not run normally, so if you're expecting saving for example, it won't happen after this piece of code.
I've created a variable within a function it looks like this:
function my_plugin_options() {
//must check that the user has the required capability
if (!current_user_can('manage_options'))
{
wp_die( __('You do not have sufficient permissions to access this page.') );
}
// variables for the field and option names
$opt_name = 'mt_favorite_color';
$hidden_field_name = 'mt_submit_hidden';
$data_field_name = 'mt_favorite_color';
// Read in existing option value from database
$opt_val = get_option( $opt_name );
doingthistest($opt_val);
// See if the user has posted us some information
// If they did, this hidden field will be set to 'Y'
if( isset($_POST[ $hidden_field_name ]) && $_POST[ $hidden_field_name ] == 'Y' ) {
// Read their posted value
$opt_val = $_POST[ $data_field_name ];
// Save the posted value in the database
update_option( $opt_name, $opt_val );
// Put a "settings saved" message on the screen
?>
<div class="updated"><p><strong><?php _e('settings saved.', 'help-menu-settings' ); ?></strong></p></div>
<?php
}
// Now display the settings editing screen
echo '<div class="wrap">';
// header
echo "<h2>" . __( 'Help block details', 'help-menu-settings' ) . "</h2>";
// settings form
?>
<form name="form1" method="post" action="">
<input type="hidden" name="<?php echo $hidden_field_name; ?>" value="Y">
<p><?php _e("Whatever:", 'menu-test' ); ?>
<input type="text" name="<?php echo $data_field_name; ?>" value="<?php echo $opt_val; ?>" size="20">
</p><hr />
<p class="submit">
<input type="submit" name="Submit" class="button-primary" value="<?php esc_attr_e('Save Changes') ?>" />
</p>
</form>
<span><?php echo $opt_val ?></span>
</div>
<?php
}
Now I can echo out the $opt_val variable within the scope of that function but i'm struggling to access it outside.
You'll see where I set the variable $opt_val = get_option( $opt_name ); below it I pass it to a function doingthistest($opt_val); then I create an action below so I can call it in another page (WordPress method).
So my action below looks like:
add_action('testingthis', 'doingthistest');
function doingthistest(t) {
var_dump(t);
}
for some reason, the variable isn't getting passed to my action. Am I misunderstanding something?
I call it in another page like this:
<span>info is there: <?php do_action( 'testingthis' ) ?></span>
if you want something to be available in a different page (therefore presumably during a different HTTP request?) then you'd have to put it into a session variable or other persistent storage (e.g. file, database) and the retrieve it from there in your other page. HTTP is inherently stateless and the server won't remember the value of your variables from one request to the next unless you use one of the above mechanisms to store them.
Calling doingthistest($opt_val); within the context of the code you posted will dump the variable onto that page. But then if you call that same method from another page entirely - which must by definition be in a different request - it doesn't automatically remember what you the value of it was last time. It's a separate request with a separate context.
I don't understand the Wordpress stuff precisely, but I suspect your action would be better looking something like this:
add_action('testingthis', 'doingthistest');
function dosomething($o) {
var_dump(get_option( $opt_name ));
}
But obviously you'd have to set the value of $opt_name somehow. In your sample code it's hard-coded but I don't know if that's really how you're setting it in the finished solution.
I have made a site in Wordpress.
In my front-page.php and in my index.php files I entered both post and get methods just to echo a message in page-message.php file.
When I click the subscribe button the posts page:news appears.The posts page:news is defined in my Wordpress settings: dashboard=>settings=>reading=>Front page displays=>a static page.
In page-message.php I wanted to show the data I had entered from this form. T
Code for the forms:
<h2>Sign to Newsletter</h2>
<form action="page-message.php" method="post">
Name:<input class="input" type="text" name="name" value=""/><br/>
Email:<input type="text" name="email" value=""/>
<br/><input class="submit" type="submit" value="Subscribe"/>
</form>
Code for page-message.php:
<?php
$name = $_POST["name"];
$email = $_POST["email"];
echo 'Congratulations!You have been successfully subscribed to our newsletter' .$name .$email;
?>
When I click the subscribe button my url changes to http://localhost/wordpress/page-message.php?name=stergios&email=something%40someone.com.
This seems to be correct when using the post method. The problem is the content!
It always loads the news (posts page from settings =>reading) and not the simple echo message?
It always shows the posts page when I write anything beyond my pages in the url. For example the url localhost/wordpress/hhhhhhhhhhh (a page that does not exist) does load the posts page and not a message error!
if "page-message.php" is a custom template in your theme you can get the page ID where it is assigned to with following query:
$get_message_pageId = new WP_Query(array(
'post_type' => 'page',
'meta_key' => '_wp_page_template',
'meta_value' => 'page-message.php'
));
and then you can set the action with:
action="<?php echo esc_url( get_permalink( $get_message_pageId->posts[0]->ID ) ); ?>"
so you will always have the correct URL in your form, but it will only work if you have 1 page where this template is assigned to
I know the reason why it is not working.
action="page-message.php"
your static page's path should be /wp-content/themes/{themename}/page-message.php u can try it,
action="<?php echo get_template_directory(); ?>/page-message.php"
But I don't think it will work. You can try
action="/index.php"
It is untested. let me know if it work.
Update: As you set that page as front page, then your wordpress root url will be that page's url (example.com or example.com/wpdirectory). Then simply do it,
action="/"
or
action="/wpdirectory"
I've added my HTML page as part of the admin wordpress (see screenshot)
And I'm trying to get it so on each submit button, if the record is successfully added to the database a pop up shows up saying "Success!" and then clear the form data without leaving the page. At the moment my current set up tries to load the external page instead of remaining on the page in the screenshot. Here's my HTML and PHP:
<form class="pure-form" name="addAthlete" action="submitForm.php" method="POST">
<fieldset class="pure-group">
<input type="text" class="pure-input-2" name="membershipID" placeholder="Membership ID">
<input type="text" class="pure-input-2" required="required" name="firstName" placeholder="First Name">
<input type="text" class="pure-input-2" required="required" name="surname" placeholder="Surname">
</fieldset>
<button name="submitAthlete" type="submit" class="pure-button pure-input-2 pure-button-primary">Submit</button>
</form>
<?php
function showSuccess() {
echo "Success! One record added.";
}
if (isset($_POST['submitAthlete'])) {
addAthlete();
}
function addAthlete() {
include 'addAthlete.php';
showSuccess();
}
?>
I'm assuming the problem lies with the fact that the echo "Success" is trying to echo on the submitForm.php page which is how I've written it. This is because of the way the page is embedded into wordpress, you can see this below:
add_action( 'admin_menu', 'db_menu' );
function db_menu() {
add_menu_page(
'Database Form', // page title
'Database Form', // menu title
'manage_options', // capability
'database-form', // menu slug
'wpse_91693_render' // callback function
);
}
function wpse_91693_render() {
global $title;
print '<div class="wrap">';
print "<h1>$title</h1>";
$file = plugin_dir_path( __FILE__ ) . "submitform.php";
if ( file_exists( $file ) )
require $file;
print '</div>';
}
How can I get a pop up or something to show up within this WordPress page on each submit?
Thanks!
When you submit a form, it posts data to a new webpage by loading it. In order to stay on the same page, the action should take you to that same page ( move your processing logic there aswell, checking for posted arguments ) or if you don't want to see a reload, use ajax instead.