add_action in different location - Wordpress - wordpress

I have a function that when it comes to calling from another plugin I call it this way
add_action( 'du_postSaveEvent', [ 'Lever\Api\Providers\ShareService', 'postSaveEvent' ], 10, 3 );
This works while in a plugin path.
/public_html/wp-content/plugins/
But if I call it from a page that is in
/public_html/wp-content/themes/
the thing changes and I can not execute said action
How should the action change?
The function to call is inside a plugin and has this structure.
public static function postSaveEvent ( $new_status, $old_status, $post ) {
}
Note:
That is, if I call that function from another plugin that is inside the plugins/ folder works.
But if I call it from a page that is in themes/ it doesn't work.

This is most likely because in the WordPress lifecycle, plugins are loaded before the themes and can therefore execute code earlier and access more lifecylce hooks which are not available for themes.
Depending on when the hook "du_postSaveEvent" is executed, you will not be able to access it via theme, because when the theme is loaded the code already ran.
You find the lifecyle docs here:
https://codex.wordpress.org/Plugin_API/Action_Reference
If you develope a plugin that runs hooks with "do_action", it is best to implement them in a hook that is run after the "after_setup_theme".
(e.g. 'init')
If you don't have access to when "du_postSaveEvent" is ran, you best use a plugin to add more functions to it. Since there is no way for your theme to access it.

Related

Does wordpress clean up your action hooks?

I've written a Wordpress plugin. I hook to some actions from another plugin and everything works, but I want to know, when I deactivate my plugin, do these actions still get called and executed, or does Wordpress remove them automatically?
I tried removing actions on deactivate hook, but something doesn't make much sense to me. I'm using OOP.
When adding an action, I add the callable with an array like this in a registerActions function:
add_action('gform_validation_' . $form_id, array($this, 'formValidate'));
and remove it in unregisterActions function:
remove_action('gform_validation_' . $form_id, array($this, 'formValidate'));
My problem:
The registerActions and unregisterActions functions are called to different instances of the same class. Is remove_action actually removing the same action I've created?
I couldn't find anything discussing this on the internet and it really left me wondering.
Edit: I guess I could store the instances and actually call the registerActions and unregisterActions functions on the same instance. But how do I do it properly? I could also make action functions static.

Running PHP code before loading template in Wordpress

Since I've only started using Wordpress recently, I'm still trying to figure how to run PHP code prior to loading the template for a particular post.
I'm talking about code which would be executed in the contoller class in a MVC structure.
Obviously it's tempting to stuff it in the page's template file, but I'm sure this won't be exactly qualified as best practice.
Any suggestions on this matter? Many thanks.
The actions(list of executing) on front part WordPress:
muplugins_loaded
registered_taxonomy
registered_post_type
plugins_loaded
sanitize_comment_cookies
setup_theme
load_textdomain
after_setup_theme
auth_cookie_malformed
auth_cookie_valid
set_current_user
init
widgets_init
register_sidebar
wp_register_sidebar_widget
wp_default_scripts
wp_default_styles
admin_bar_init
add_admin_bar_menus
wp_loaded
parse_request
send_headers
parse_query
pre_get_posts
posts_clauses
posts_selection
wp
template_redirect
get_header
wp_head
wp_enqueue_scripts
wp_print_styles
wp_print_scripts
get_search_form
loop_start
the_post
get_template_part_content
loop_end
get_sidebar
dynamic_sidebar
get_search_form
pre_get_comments
wp_meta
get_footer
get_sidebar
wp_footer
wp_print_footer_scripts
admin_bar_menu
wp_before_admin_bar_render
wp_after_admin_
bar_render
shutdown
So, if You need some magic without all core functions, You can put your code into own mu-plugin for example, and it will execute on start(muplugins_loaded action).
For basic functionality and with theme functions - wp_loaded, etc. see the list above.
Usual, uses init action(cause WordPress is fully loaded, but without header and other stuff), example:
add_action( 'init', 'my_func' );
function my_func() {
// Write some code here...
}

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.

WordPress using different CSS - is this possible?

Bit is a basic question here but can someone confirm that this statement be confirmed: WordPress Pages (certain templates created within) can pull different CSS and JS?
Or - does WordPress only permit universal CSS + JS to be pulled across the entire site?
Thanks for clearing this up.
Depends on what plugin and themes you use. The WordPress/PHP functions wp_enqueue_style() and wp_enqueue_script() can be used literally by everyone (core, themes, plugins, you) to request WordPress to load styles or JavaSctript. You can combine this with WordPress functions to check whether the current page is something you want to filter for (post type, post, front-page, category archive, template, etc.). Here is an example to load a custom style if on front page :
if (is_front_page()) {
wp_enqueue_style('custom-frontpage', 'my/path/to/frontpage.css');
}
You will have to hook this piece of code to the wp_enqueue_script action so that WordPress executes it at the appropriate time. Here is an example using an anonymous function:
add_action('wp_enqueue_scripts', function() {
if (is_front_page())
wp_enqueue_style('custom-frontpage', 'my/path/to/frontpage.css');
});
You can also register your code as a "normal" function and pass the functions name to add_action() instead.
Edit: Enabling and disabling plugins is a bit more difficult, since you can never know how they implement their features without examining the source code. Here are my thoughts on this:
The plugin likely uses the above method (wp_enqueue_styles, wp_enqueue_scripts) to register it's styles and scripts. The plugin, since it assumes to be needed on all pages and posts, does this on every page without the conditional checking described earlier.
You could do one of the following to stop the plugin from doing this:
Identify the place where the plugin loads the styles and scripts and add the if-statement to only do so if the post-ID matches your desired post-ID. This method is bad since your changes are lost every time the plugin is updated.
Write a "counter plugin" (you could just add it to your theme or find a plugin that allowes you to add PHP to your page) that "dequeues" the style and script added by the plugin with inversed conditional tag
The counter-plugin approach would look as follows:
function custom_unregister_plugin() {
if (not the desired blog post) {
wp_dequeue_style('my-plugin-stylesheet-handle');
wp_dequeue_script('my-plugin-script-handle');
}
}
Make sure this function is executed after the enqueuing-code of your plugin by giving it a low priority in the same hook (999 is just an example, test it yourself):
add_action('wp_enqueue_scripts', 'custom_unregister_plugin', 999);
With wp_enqueue_style() you can add stylesheet (https://developer.wordpress.org/reference/functions/wp_enqueue_style/)
You can use it after detecting which template is used
function enqueue_custom_stylesheet() {
if(get_page_template() == 'contact.php')
wp_enqueue_style( 'contact-style', get_template_directory_uri().'/contact.css' );
}
add_action( 'wp_enqueue_scripts', 'enqueue_custom_stylesheet' );
You can use wp_enqueue_style for your CSS, wp_enqueue_script for your JS, wp_localize_script to pass variables from PHP to JS.
You can call these with hooks like:
funtion enqueue_my_stuff()
{
// your enqueue function calls
}
add_action('wp_enqueue_scripts','enqueue_my_stuff'); //front end
add_action('admin_enqueue_scripts','enqueue_my_stuff'); //admin panel
add_action('login_enqueue_scripts','enqueue_my_stuff'); //login screen

Wordpress plugin functions: check if function exists

I'm developing a Wordpress site that relies on a plugin to be activated for the site to function properly.
The plugin has a few useful functions that I'm using in the site's template files. When the plugin is active, everything works perfectly. If the plugin is deactivated, the content doesn't load.
Wrapping these functions in if(function_exists(...) obviously fixes that, but I'm wondering if there's a cleaner way of doing that in Wordpress. Is there a function that can be placed in the theme's functions.php file that can check if these functions are available every time I call them, and if not provide a safe fallback without me having to wrap them in the function_exists()?
Thanks.
If you're only using it sparingly (1-2 times), use if( function_exists() ). If you're calling the function several times through in different template files, I'd suggest using something like
In your functions.php
function mytheme_related_posts( $someparams = nil ) {
if( function_exists( 'related_posts' ) ) {
related_posts( $someparams );
} else {
echo 'Please enable related posts plugin';
}
}
Then use mytheme_related_posts() in your template.
I think this is the most clear way. It prevents all problems. I think you can write a function instead which can check if these functions are available every time you call them, but I'm almost sure it can cause you more trouble and it burns more memory then simply using if(function_exist()). Don't forget the else branch and it will work fine.
If you want to check if a plugin is active then you should be using the is_plugin_active() function - you can find the docs at: http://codex.wordpress.org/Function_Reference/is_plugin_active
You can then also use if(function_exists()) as well just to doubly make sure :)

Resources