Running PHP code before loading template in Wordpress - 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...
}

Related

add_action in different location - 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.

Theme Action to hook for one time only function

I am developing a custom theme. After my theme is activated/installed I need to run a one time only function that will set some options. What is the best action to hook for this?
Should I use after_setup_theme? My understanding is that this event/action fires on each page load so I don't think I should use this action correct?
*Ps: is it best to place this code in my functions.php file or somewhere else? (I am using the underscores theme template).
You should look at after_switch_theme action. It'll fired only on your theme activation( just one time ). So, your one time function will look:
add_action('after_switch_theme', 'my_one_time_function');
function my_one_time_function () {
//Your code
}
Code goes to functions.php file.
P.S. If you want to run some function before deactivating theme, you can use switch_theme hook. It has same use as after_switch_theme.

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 ajax for a plugin only works when defined in the active theme

I'm testing with very simple code to try and get ajax working from within a plugin I'm writing. However I always get the dreaded 0 returned from the admin-ajax.php file.
The basic code defined in my plugins main php file is:
// Init custom actions
add_action( 'wp_ajax_import_run', 'import_run' );
function import_run() {
echo "testing 123";
die();
}
And then import_run is the action parameter parsed via the jquery ajax call.
Now the funny thing is, this works fine when I place the above php code in the themes main function.php file, but whenever I place the code in the actual plugin where it's needed it won't work. The issue is it needs to be in the plugin, not the theme.
So it seems I'm missing some small vital step about where to put my add action and function within the plugin. Any ideas?
you haven't provided your complete code in your plugin.
You can't invoke plugin function using wp ajax call.
Here's a simple WP plugin code to display some text everywhere.
<?php
/**
* #package Testplugin
*/
/*
Plugin Name: Testplugin
Plugin URI: someuri
Description: To demo a simple plugin
Version: 2.5.8
Author: Automattic
Author URI: http://automattic.com/wordpress-plugins/
License: GPLv2 or later
*/
function pluginnamehere() {
echo "This gets displayed everywhere";
}
add_action( 'plugins_loaded', 'pluginnamehere' );
I've worked out what was going on. I was adding the add_action hook everywhere but in the core root plugin page. Previously I had been adding it to a secondary php file that I thought was the root plugin file but wasn't.
The confusion occurred because I'm using a boilerplate empty plugin template to work with, so even though the plugin does very little so far its actually full of code and remarks already.

finding do_action function

I've got this.
do_action( 'bp_before_directory_groups_list' );
and I cant find the corresponding add action to trace the function that is called. Anyone know what im doing wrong?
Mark
Maybe there isn't one, as it may be just there so as to enable other plugins to hook into it But to check, run this code after loading all the plugins, like in a theme file:
print_r($wp_filter['bp_before_directory_groups_list']);
$wp_filter is a global variable that stores all the action hooks and filters added by plugins.

Resources