Global variables vanish in WordPress plugin - php

I'm writing a WordPress plugin. I want to display a custom message after a post is saved. This message will depend on the outcome of function called when the post is saved.
Here's my code:
add_action('save_post', 'my_save_post_function');
function my_save_post_function() {
global $msg;
$msg = "Foo bar";
...
}
add_filter('post_updated_messages', 'my_post_updated_messages_function');
function my_post_updated_messages_function($messages) {
global $msg;
$messages["post"][1] = $msg; // !! $msg is undefined !!
...
}
Why is $msg undefined?
Is there any way I can get a result out of a save_post action? I've tried all sorts of tricks. Even the $_POST data seems to have been blown away by the time admin messages are shown.

have you tried session ? i think your problem will be fixed .
take a look at :
http://www.php.net/manual/en/function.session-start.php

Related

How to Make a PHP Variable Return Text Instead of Nothing

My code needs to see and use the text held in a variable:
I'm working on a WordPress plugin. One section of it needs to place text above the website's login form. If I just type in text as in the code below (return "My New Header Text";) it works fine and "My New Header Text" appears above the form.
// Add a CUSTOM MESSAGE to the top of the WordPress login form
function new_plugin_login_message( $message ) {
if ( empty($message) ){
return "My New Header Text";
} else {
return $message;
}
}
add_filter( 'login_message', 'new_plugin_login_message' );
But when I use a variable that includes the text, as in: (return "$MyNewMessage";) it won't work. Below is what I have. Even with lots of experimentation and Googling, I can't find a way for it to actually take the text stored in the variable and place it above the form. How do I make it see and use the text that is in the variable, "$MyNewMessage"?
// Add a CUSTOM MESSAGE to the top of the WordPress login form
function new_plugin_login_message( $message ) {
if ( empty($message) ){
return "$MyNewMessage";
} else {
return $message;
}
}
add_filter( 'login_message', 'new_plugin_login_message' );
This must be easy, but it eludes me. Thanks for any assistance.

Session based flash message doesn't work in else part of PHP code

In my contact.php page, I am sending emails to admin and user after passing the validation. The code looks something below:
// If any validation error occurs
if(count($errors) > 0)
{
// show error messages
}
else
{
// sending emails to admin and user
set_flash_msg('msg', 'Thank you for contacting us.', 'success');
redirect_to('contact');
}
But the code in else part related flash message doesn't work. If I put this code in if part then it works without any issue. The function set_flash_msg() is responsible to create session based flash message. Its code is below:
// Set flash message
function set_flash_msg($name, $msg, $class)
{
global $name;
if(empty($_SESSION[$name]) && empty($_SESSION[$name . '_class']))
{
$_SESSION[$name] = $msg;
$_SESSION[$name . '_class'] = $class;
}
}
To display this message, another function is called below the above code as:
// Show flash message
get_flash_msg();
There is no issue regarding session setting because in if part, it works fine. The same logic and coding flow is used in my backend too where I set flash message when a new page is added and show the flash message on page listing page.php. If it works at there then why it doesn't work on my front-end contact.php page? Any idea?
In my contact.php page, I am grabbing the form values particularly "name" as:
// Preparing form variables
$name = isset($_POST['txtname']) ? $db_obj->sanitize_input($_POST['txtname']) : '';
The local variable $name conflicts with global variable $name in set_flash_msg() function. Changing $name to $uname in above code solved the problem.

Call function from another page in php

I have a form that user can update their details on page-1.php.
After user submit the form, it will got to page-2.php for validation and update database if user input is true.
May i know how to call a function from page-2.php and display the error message on page-1.php. Below are the function on page-2.php that I use to display the error message:
$_SESSION['err_msg'] = array();
function addError($msg) {
$_SESSION['err_msg'][] = $msg;
}
function printErrors() {
foreach ($_SESSION['err_msg'] as $err){
echo "<ul><li><span style='color: red;'>".$err."</span></li></ul>";
}
unset($_SESSION['err_msg']);
}
//other codes for the validation and update
if i use printErrors();on page-2.php, it will display the error message
You need to include page-2.php in page-1.php. Read this about that.
The best way is to put all your functions in one seperate file, like functions.php and include them on every page with an include.
I think no you don't need function on page-2.php. You can simply check session variable on page-1.php. If $_SESSION['err_msg'] exists and count is greater than 0. Then you can print all errors to page-1.php>
Please check below code.
if(isset($_SESSION['err_msg']) && count($_SESSION['err_msg'])>0 ){
foreach ($_SESSION['err_msg'] as $err){
echo "<ul><li><span style='color: red;'>".$err."</span></li> </ul>";
}
unset($_SESSION['err_msg']);
}
Hope this helps you.
Include the page-2.php in your page-1.php

In PHP, is there an alternative to putting # in front of functions whose variables are defined later? Explanation + code inside

I'd like to preface this by saying that I've read answers to similar questions, and haven't managed to find something that both does the job and does not slow the site down.
I have a site that displays messages based on users' choices and actions. The code might look something like this :
if (option 1) {
$message1 = "Message A";
}
else if (option 2){
$message1 = "Message B";
}
else {
$message1 = "Message C";
}
There are a hand full of these throughout the site. When i want to echo the messages somewhere within the html structure i have to write:
<?php
if (isset($message1)) {
echo $message1;
}
?>
I've written a simple function which does its job:
function message($msg){
if (isset($msg)) {
echo $msg;
}
}
The problem is that i get notices for undefined variables, which makes sense because the variable isn't defined before the user clicks a button. I would like to avoid turning off error reporting.
So, is adding # in front of the function the only way? The code would then look like:
<?php
#message($message1);
?>
If that is acceptable, then great. If not, I'm open to alternatives.
Based on your comment, your use-case seems to make sense. In that case I would have an array with all error messages, something like:
$messages = array();
...
$messages['registration-form']['error']['password-mismatch'] = 'Passwords do not match';
...
And when I validate the input and find mismatching passwords, I would do:
// at the top
$errors = array();
...
// passwords don't match
$errors['passwords-mismatch'] = $messages['registration-form']['error']['password-mismatch'];
And where I output the form below the passwords:
messages($errors, 'password-mismatch');
And finally the function would be something like:
function messages($errors, $error) {
if (isset($errors[$error])) {
// I would wrap it in a span to highlight the error
echo '<span class="error">' . $errors[$error] . '</span>';
}
}
You can pass the variable by reference, function message(&$msg){, no error will be raise.
From the documentation:
If you assign, pass, or return an undefined variable by reference, it will get created.
Try this php in built function:
error_reporting(0);

wordpress contact form 7 disable email

I am facing an issue with Contact Form 7 for Wordpress. I want to disable the email notification which i did using
demo_mode: on
At the same time i want to redirect on submit which i used to do using
on_sent_ok: "location = 'http://domain.com/about-us/';"
Both would work when used individually.But i want to use both at the same time.
I tried doing
on_sent_ok: "location = 'http://domain.com/about-us/';"
demo_mode: on
Doesnt seem to work. Kindly advice.
The plugin author has changed as of at least 4.0 the way you should do this again. The skip_mail property is now private :
class WPCF7_Submission {
private $skip_mail = false;
...
}
You should use this filter : wpcf7_skip_mail
For example :
function my_skip_mail($f){
$submission = WPCF7_Submission::get_instance();
if(/* YOUR TEST HERE */){
return true; // DO NOT SEND E-MAIL
}
}
add_filter('wpcf7_skip_mail','my_skip_mail');
The author of the plugin Contact Form 7 has refactored some of the code for its version 3.9 and since then the callback function for the hook wpcf7_before_send_mail must be written differently.
To prevent Contact Form 7 from sending the email and force it to redirect after the form has been submitted, please have a look at the following piece of code (for version >= 3.9):
add_action( 'wpcf7_before_send_mail', wpcf7_disablEmailAndRedirect );
function wpcf7_disablEmailAndRedirect( $cf7 ) {
// get the contact form object
$wpcf7 = WPCF7_ContactForm::get_current();
// do not send the email
$wpcf7->skip_mail = true;
// redirect after the form has been submitted
$wpcf7->set_properties( array(
'additional_settings' => "on_sent_ok: \"location.replace('http://example.com//');\"",
) );
}
Hook into wpcf7_before_send_mail instead of using the flag .
add_action("wpcf7_before_send_mail", "wpcf7_disablemail");
function wpcf7_disablemail(&$wpcf7_data) {
// this is just to show you $wpcf7_data and see all the stored data ..!
var_dump($wpcf7_data); // disable this line
// If you want to skip mailing the data..
$wpcf7_data->skip_mail = true;
}
Just an update. The following works in 4.1.1.
on_sent_ok: "location = 'http://domain.com/about-us/';"
demo_mode: on
Set skip_mail: on does the trick.
There might have been a change to contact-form-7, because I wasn't able to access the $skip_mail variable in the WPCF7_Submission object. I looked at the submission.php object in the \wp-content\plugins\contact-form-7\includes\submission.php file and found this:
private $skip_mail = false;
Since the variable is private, and there are no getters or setters in the file, you're not going to be able to change it externally. Just change it to this:
public $skip_mail = false;
and then you can change the variable like this in your functions.php file:
add_filter('wpcf7_before_send_mail', 'wpcf7_custom_form_action_url');
function wpcf7_custom_form_action_url( $form)
{
$submission = WPCF7_Submission::get_instance();
$submission->skip_mail = true;
}
A reminder, if you update the contact-form-7 plugin, it will probably nullify your change, so keep that in mind.
Simple code
Copy and paste the following code in your activated theme functions.php file.
add_filter('wpcf7_skip_mail','__return_true');
UPDATE WPCF7 ver. 7.5: There is now a filter specifically to handle this.
function my_skip_mail($f){
$submission = WPCF7_Submission::get_instance();
$data = $submission->get_posted_data();
if (/* do your testing here*/){
return true; // DO NOT SEND E-MAIL
}
}
add_filter('wpcf7_skip_mail','my_skip_mail');

Categories