Triggering the Advanced Custom Fields (ACF) 'acf/save_post' Action - wordpress

I've read the ACF 'acf/save_post' documentation here: acf-save_postDocs, which states this action enables one to add additional functionally before or after saving/updating a post. I want to test when this action is triggered.
I created a custom post type and a collection of ACF custom fields that are linked to this custom post type.This includes some ACF custom field types that I created using the ACF Starter Kit (see: creating-a-new-field-typeDocs), and they are used for some of the ACF custom fields. When I edit a custom post and then click the 'Update' button in the Gutenberg editor, I expect the 'acf/save_post' action to fire, but it does not seem to do so. Perhaps I am missing something. Here is the relevant code from my theme's 'function.php' file.
function my_acf_save_post($post_id) {
console_log("Testing...");
}
add_action('acf/save_post', 'my_acf_save_post', 20);
function console_log($output, $with_script_tags = true) {
$js_code = 'console.log(' . json_encode($output, JSON_HEX_TAG) . ')';
if($with_script_tags) {
$js_code = '<script>' . $js_code . '</script>';
}
echo $js_code;
}
Citation for the 'console_log' function: Kim Sia (see: https://stackify.com/how-to-log-to-console-in-php/).
I have my web browser's inspector window opened for my custom post type post's editor. After modifying the post and clicking 'Update', nothing displays in the inspector's console pane. I posted about this in the ACF forum but have received no response.
Your feedback is appreciated. Thank you.

Find below the instructions of how to debug that ACF hook in WordPress.
Official document for further details: https://wordpress.org/support/article/debugging-in-wordpress/
Note that there are other, more sophisticated and efficient ways of debugging in WordPress, for example using a proper debugger like xdebug.
These are usually harder to setup though, so here I am giving you the "WordPress in-built" way that might be simple, but is easy and effective.
ENABLE DEBUGGING
First, you need to enable debugging in wp-config.php, which I think you already did, but for others reading this answer, what you should do is:
Open in a text editor the file called wp-config.php, located in the wordpress installation root
Add the following to this file:
define('WP_DEBUG', true); => This enables debugging
define('WP_DEBUG_DISPLAY', false); => This prevents error logging from displaying on screen (affects both frontend and backend)
define('WP_DEBUG_LOG', true); => This logs the output to a file where you can then check it
You must add these yes or yes above the line
/* That's all, stop editing! Happy blogging. */
Done! Now you are logging, by default, to a file that will get generated in the root of the wp-content directory named debug.log.
WARNING! It is recommended to not leave debugging enabled on Production environments, as well as it is recommended to not leave the debug.log file as it could leave sensible site information exposed. Use for development only, and disable and remove file when finished. File can also be saved to a custom file name and location, see docs.
ERROR LOG
console.log is usually used for debugging js.
To log your function in PHP using the enabled debugger above, do the following:
function my_acf_save_post($post_id) {
error_log( 'Saved post ID : ' . $post_id, false);
error_log( var_export($_POST, true), false );
//If you want to log what got saved to the database
error_log( var_export(get_post($post_id), true), false );
}
add_action('acf/save_post', 'my_acf_save_post', 20);
You should find the saved post data and the ACF data recorded in a file named debug.log in your wp-content directory root.
LOGGING TO SCREEN
If instead what you want is to see the output that would have got written to the file, but directly on the screen, you don't need error_log() function, and instead you do that as shown below:
function my_acf_save_post($post_id) {
echo 'Saved post ID : ' . $post_id;
// Add <pre> tags to format the output in an easily readable way:
echo '<pre>';
print_r($_POST);
echo '</pre>';
}
add_action('acf/save_post', 'my_acf_save_post', 20);

Related

Wordpress errors from shortcodes being executed on edit page

I am writing a wordpress plugin.
I have noticed in my debug log that i get a lot of PHP errors thrown because my shortcodes are being executed on the admin edit pages and therefore the relevant data is not available because the shortcode is loading dynamic data based upon the user front end. For example i have a function:
function myFunction_availability() {
if (is_admin()) return; // tried adding this but still get the issue
$product = $this->myFunction_get_current_product();
return "<div class='product-availability'>{$product->availability}</div>";
}
Works fine from the front end, but whenever i load the edit page from admin area i get in my log:
PHP Warning: Attempt to read property "availability" on null in /home/vagrant/yodahwp/wp-content/plugins/yodah/class.yodah.php on line 1602
As you can see from my code, i tried adding is_admin() to exit out of the function if viewing an admin page (i.e. the edit post page) but this does not seem to work.
Do any wordpress whizzes have an answer for this? I am a bit surprised that shortcodes are executed on the admin edit pages, or am I missing something?!
Thanks
This is an old question. Usually, this happens when using visual builders.
One solution is to write a condition to check if the product exists.
If using woocommerce you can try:
$product = wc_get_product( get_the_ID() );
if($product){
//continue
}
In your case, you should edit your myFunction_get_current_product() method and verify there if the product exists.

Single Post Template Override for Custom Post Type

I've got kind of a unique scenario that I'm trying to nail down. I'm working on a new template for a custom post type that already exists. Basically, we're replacing the single-customposttype.php file with a new one. All of that is going swimmingly, except one thing - they have one post in that custom post type that they want to keep the OLD template on.
So there's a NEW single-customposttype.php file that will work as the default single template for that CPT.
But I need ID #93 to use the OLD single-customposttype.php template. I hoped just doing single-customposttype-93.php might do the trick, but it doesn't. What's the best way to apply the other template to only one post id?
Thanks in advance!
I deal with custom template loading all the time, it's really pretty simple! Really, all you need to do is hook into the template_include hook, and override the template based on whatever conditions you want.
That hook takes a single argument, the $template file to load. You can then use any conditionals you want and force a separate file to load instead.
add_filter( 'template_include', 'custom_template_include', 99 );
function custom_template_include( $template ){
// For ID 93, load in file by using it's PATH (not URL)
if( get_the_ID() === 93 ){
// Note the file name can be ANYTHING, the WP auto-template names don't matter here
$file = get_stylesheet_directory() . '/post-id-93-custom-template.php';
// It's generally good to see if the file exists before overriding the default
if( file_exists( $file ) )
$template = $file;
}
// ALWAYS return the $template, or *everything* will be blank.
return $template;
}
It's really that simple! Inside the custom PHP file, you have access to all of the WordPress functions and such as you would with a default template.
Generally you'll want to use the file_exists() function on the template, just to make sure it's found, otherwise you'll be passing along a file that doesn't exist, and that page will not load. By checking if it exists, it will still fall back to the old template if it's not found (deleted/renamed/moved, etc)
Also, you always need to have return $template at the end, otherwise anything that uses WordPress' template system will break.
I made a quick example on a demo site:
https://xhynk.com/content-mask/policies/cookie-policy/
https://xhynk.com/content-mask/policies/use-another-template/
The policies are a custom post type, and the cookie policy loads normally. The other one is modified with the same code as above (with the name/ID changed to match), and it's loading in a simple .php file with that content in it.

How to attach files to an email sent by a WordPress booking plugin?

I'm using a WordPress plugin for accepting online bookings (Appointment Hour Booking) and I need to attach a file to the emails sent after submitting the booking request (a PDF file with the general booking terms). I already applied a solution by editing the calls to the wp_mail() function in this way:
wp_mail(trim($payer_email), $subject, $message,
"From: ".$from."\r\n".
$content_type. "X-Mailer: PHP/" . phpversion(),
array(WP_CONTENT_DIR . '/uploads/agreement.pdf'));
The above works but everytime the plugin updates the file is overwritten and I've to reapply the code modification again. There is a better way to do that without being affected by the plugin updates or there is a way to prevent partially or completely a plugin update in WordPress?
Thank you in advance for any help.
Disabling the plugin update isn't a good idea, you may lost important compatibility or security updates. The way the call to the wp_mail() was modified also causes other attachment-related features stop working. The plugin you mention has a filter that can be used to modify the list of attached files, you can put the following code for example into your theme’s functions.php file:
add_filter( 'cpappb_email_attachments', 'my_attach_function', 10, 3 );
function my_attach_function( $attachments, $params, $form_id )
{
$attachments[] = WP_CONTENT_DIR . '/uploads/agreement.pdf';
return $attachments;
}
With the above code located out of the plugin files your file is added to the list of attachments without removing other attachments and locating the code out of the plugin files will prevent being overwritten by the plugin updates.
Your options are:
Fork the plugin and customize it to your needs.
Ask the team behind the plugin to implement a filter hook to allow customizing the headers passed to the wp_mail() function (so you can then attach files to e-mails).
Keep doing what you have been doing until now.
I like option two the best because:
It allows you to customize the behavior of the plugin from the outside, and,
Your changes will survive plugin updates.

wp_redirect not working in custom plugin

I am trying to create custom plugin in wordpress.
We want to create a case like if user is not logged in to the system then user should be redirected login page. I tried wp_redirect and wp_safe_redirect but it is not working. here is my code.
if (isset($_SESSION['game_login'])) {
//Do Something
}else{
wp_redirect('login');
exit():
}
I am getting this warning
Cannot modify header information - headers already sent by (output started at wp-includes/class.wp-styles.php:225) in wp-includes/pluggable.php on line 1216
can someone suggest me in this scenario?
You shouldn't just start output buffers wherever unless you're specifically delaying the final output, such as modifying content on the template_redirect, using add_shortcode, or any numerous scenarios where you intend to buffer the output.
The code in your example should be encapsulated in a function and hooked to one of WordPress' many Action Hooks. Typically this kind of function is added on the plugins_loaded or init hooks.
add_action( 'init', 'redirect_anonymous_users' );
function redirect_anonymous_users(){
if( isset( $_SESSION['game_login'] ) ){
// Do Something
} else {
wp_redirect('login');
exit();
}
}
There may be several reasons causing this issue.
Try this points and hope this may have a fix
Remove blank space from files that are showing error after php ?> tag at end of file, But in your case
it is from core file, So don't modify anything in terms of code just try to remove blank space at the
ending of those files. Also remove blank space from bottom of files
wp-config.php and functions.php
If the above point does not work add this code to your wp-config.php file
ob_start();
error_reporting(0);

Custom action on user_register hook in WordPress

I try to implement a custom function/action after a new user profile has been created in WordPress. To test the code I try to write a text in a file as proof of function execution.
Here is the code that I have inserted at the end of the active theme's functions.php file
if ( ! function_exists( 'register_for_cmsa' ) ) :
function register_for_cmsa($user_id) {
// write in an external file
// writeLogWP($msg) is a function from a file I have included in index.php
writeLogWP("A new user is: " . $user_id);
}
add_action('user_register', 'register_for_cmsa');
endif;
Therefore, I added a new user through the admin panel. As soon as I validate the standard WP add user form (wp-admin/user-new.php) I get a blank page, meaning that the above code is in trouble. But the user is added in the database (it is visible in the users' list if I comment my function). The trouble here is when executing the writeLogWP("A new user is: " . $user_id) statement inside the register_for_cmsa() function.
I tried to see if the statement works outside of the function, while always inside the functions.php file. And I noticed that it writes the message to the external file when I navigate in the WP site, BUT it publishes blank page as soon as I get into the admin dashboard section.
My code is accepted in 'site' side but it is in error in the 'admin' one.
The code is however not executed in the 'site' side because the hook is not triggered. It is triggered only if I go to the 'wp-admin/user-new.php' but ... I can' test it, as per the above reason.
I am really confused, glad to have your comments and, why not, solution.
Thanks
The index.php is not loaded when accessing the WordPress admin, hence the writeLogWP function is not being called in that case. Moving it to functions.php should solve the issue.

Resources