I'm creating a really huge system in PHP and I would like to make things simpler for me and probably for the future developers.
I'm looking to achieve a functionality where when a certain action is triggered in the system, a custom function is called, just the same idea used by WordPress add_action();
This is exactly what I mean,
For example in WordPress, if one needs to execute code in the header section, a hook called wp_head is used, that's
function add_script_to_header(){
echo "this one will be print in the header";
}
add_action( 'wp_head', 'add_script_to_header' );
function another_script_on_header(){
echo "this onather script on the header";
}
add_action( 'wp_head', 'another_script_on_header' );
Now that was just an example, I would like to implement the same thing with custom PHP completely independent of WordPress, which means, my code is not in any way related to WordPress.
I've tried to use callable functions in PHP, but at some point, it gets tongue-twisting
In my case, I have a class called Orders that records, payments, shift orders from one state to another, and a lot more things, I would like to have a hook or way of triggering action with a function when certain actions are triggered.
The following code indicates some of my trials
function next_order($orderId, $status, $autoApprove = 0){
// this is function that is responsible for shifting orders from one status to another
// or from one state to another
// I would like add_action() function to be linked here, so that I can track
// order status with external functions
}
function add_action( $action_name, $function_name ){
if( $action_name == "order_next" ){
call_user_func( $function_name, $action_name);
}
if( $action_name == 'order_placed' ){
// here we can place an action for that
}
if( $action_name == 'order_paid' ){
}
}
function benson_karue( $orderId ){
echo "This is the order id ".$orderId;
}
add_action( 'order_next', 'benson_karue' );
Related
I'm training on the creation / modification of wordpress plugin, to do this, I need to make a simple PHP script that performs different actions. The problem is that once the do_action is called, nothing happens.
<?php
[...]
$actions_to_do = [
'wp_ajax_lorem_ipsum'
];
foreach ($actions_to_do as $action) {
$output = do_action($action);
echo $output;
}
I've seen :
Are there any drawback of using output buffer on do_action function?
WordPress: save output of do_action in variable
And tried this trick with the ob_start() but the problem remains the same.
foreach ($actions_to_do as $action) {
ob_start();
do_action($action);
$output = ob_get_contents();
ob_end_clean();
echo $output;
}
I specify that in the state I do not test with a plugin in particular because the problem is the same whatever the plugin or the action
Think of do_action() as a placeholder for a possible action. Here is simple example to illustrate it:
<?php
// You can paste this in page.php, in header of footer, or any other place that would be easy to observe (for test purpose only!)
echo "Hello";
do_action( 'hello_name' );
echo "!";
?>
By simply placing this code and opening a corresponding page you will be presented with:
Hello!
While do_action() was executed, there were no actions associated with it.
Now without removing existing code, add the following to your functions.php file:
<?php
/**
* We register a custom action which will be processed by
* WordPress when do_action( 'hello_name' ) is executed.
*/
function my_name_is() {
echo "Tom";
}
add_action( 'hello_name', 'my_name_is' );
?>
Reloading the page should now display:
Hello Tom!
You may register multiple actions to be triggered when do_action( 'hello_name' ) function is executed using add_action() function.
I am trying to apply specific functions to a certain page ID in Woocommerce.
However, it does not seem to apply. I have looked at both Wordpress and Woommerce conditional tags (https://docs.woocommerce.com/document/conditional-tags/).
The simple code I am testing is shown below, but even that is not working.
if ( is_product()) {
echo ' HALLO sdfdsfsdfsdfsdf ';
}
I have also tried with page_id and post_id but cannot get this to work.
I have added this code to my functions.php in my child theme.
Does anybody know to to write a specific function only for a specific product page (I know the value).
Method - 1
is_page() relies on a complete global $wp_query object. If you call it before the action template_redirect has been fired, it might be impossible to get that data.
add_filter( 'template_include', function( $template ) {
if ( is_product() )
echo 'HELLO';
return $template;
});
Method - 2
The WordPress/WooCommerce conditional tags won’t work until after the wp action is fired, making it the earliest point at which you can use the tags. You can view the entire list, and the order of the core WordPress actions at the Action Reference page.
add_action( 'wp', 'init' );
function init() {
if ( is_shop() ) {
echo 'HELLO, this works!';
}
}
I am trying to call function, created with add_action using do_action:
In the function.php of the theme:
function bleute_utbi_service_type()
{
return "service";
}
add_action('utbi_service_type', 'bleute_utbi_service_type');
Now, I need to get the value of the function in a plugin file:
// 'x' plugin file:
function get_valor(){
$val = do_action('utbi_service_type');
echo "this is the valor:" . $val";
}
This way of doing is not working, $val return 'null'...why?
Action hooks do not return content, and honestly if you need an action hook to return content there is a pretty good chance that you are doing something wrong.
add_action() takes the identification of a function, in your case
bleute_utbi_service_type(), and puts it into a list of functions to be called
whenever anybody calls do_action().
Either use $params with your do_action and add_action and then set the $value in your add_action callback function or use filters to return contents. To know how return works with filters, u may refer here: Wordpress: How to return value when use add_filter? or https://developer.wordpress.org/reference/functions/add_filter/
If you want to do it with add_action than you have to follow this referenece by passing argument to add_action
Reference
else try using apply filters like this.
add above code in function.php:
function example_callback( $string ) {
return $string;
}
add_filter( 'example_filter', 'example_callback', 10, 1 );
function get_valor(){
$val = apply_filters( 'example_filter', 'filter me' );
echo "this is the valor:". $val;
}
and add below code to wherever you want to print:
get_valor();
hope it works for you :)
I created my own child theme. Everything works great except I can't seem to unregister a hoook.
$this is class TC_footer_main and the following code is in the __construct
add_action ( '__colophon' , array( $this , 'tc_colophon_center_block' ), 20 );
I tried several remove actions with no success. I am just trying to change/remove the footer:
remove_action( '__colophon' , 'tc_colophon_center_block' , 55);
or
remove_action( '__colophon' , array('TC_footer_main','tc_colophon_center_block') , 55);
I've also tried
remove_action( '__colophon' , TC_footer_main::$instance->tc_colophon_center_block() , 55);
But that threw an error as TC_footer_main was not loaded by the time my functions.php file ran.
I am just trying to change/remove the footer:
I think you're making it way more complex, to modify the output of the tc_colophon_center_block() method, than it has to be.
Just use the tc_credits_display filter:
add_filter( 'tc_credits_display', function( $html )
{
// Modify output to your needs!
return $html;
} );
to modify that block to your needs.
To totally remove the output (if that's allowed), simply use:
add_filter( 'tc_credits_display', '__return_null', PHP_INT_MAX );
You have further access to filters like:
tc_copyright_link
tc_credit_link
tc_wp_powered
to choose from.
That's it!
For your purpose add the following code in function.php. It will get call on after_setup_theme hook.
// replace parent function
function child_theme_function () {
// your code goes here
}
function my_theme_setup () {
remove_action( '__colophon', 'tc_colophon_center_block', 1000 );
add_action( '__colophon', 'child_theme_function', 1000 );
}
add_action( 'after_setup_theme', 'my_theme_setup' );
You can also try for overriding the parent class from child class as described here: https://thethemefoundry.com/tutorials/advanced-customization-replacing-theme-functions/
you werent too far away...one problem you may have is you are trying to remove the hook before it has been added by your parent theme..the class could be initialized at a later stage...
im not too sure when your hook runs, but hopefully its after init
add_action('init', 'remove_parent_hook');
function remove_parent_hook(){
remove_action( '__colophon' , array('TC_footer_main','tc_colophon_center_block') , 20); // needs to be the same priority
}
you can obviously now just add a action for your new function.
There is a offchance that a anonymous function has been added, often the significance of &$this is overlooked when trying to remove a hooked function. This is a pain because wp will assign a random string as the key name & the function name for the function, its different every time so it cant be guessed. But we can search for the function name within the key so something like this will work
function remove_anon_hk($hook, $function, $priority=10 ){
global $wp_filter;
$hooks= $wp_filter[$hook][$priority];
if(empty ($hooks))
return;
foreach($hooks as $hk=>$data):
if(stripos($hk, $function) !== false ){
unset($wp_filter[$hook][$priority][$hk]);
}
endforeach;
}
add_action('init', function(){
remove_anon_hk('__colophon', 'tc_colophon_center_block');
});
I have a big problem with wp.4.0.1. I make for a client a management company software, and everything is based on wordpress functions / plugins / actions & stuff.
class AppNoteCommand{
function AppNoteCommand() {
$this->table_note = 'wp_app_noteCommand';
$this->table_stock = 'wp_app_products_stock';
$this->instance = $this;
add_action( 'saveNoteCommand', array( $this, 'hookSaveNoteCommand'), 10, 4);
add_action( 'saveNoteCommand', array( $this, 'updatingStock' ), 20, 4);
}
function hookSaveNoteCommand( $noteFields, $clientFields, $stockFields, $dbAction ) {
global $wpdb;
printr($noteFields);
if ( $dbAction == 'update' && (int) $noteFields['id'] >0 ) {
$wpdb->update( $this->table_note, $noteFields, array( 'id' => $noteFields['id']) );
} else $wpdb->insert( $this->table_note, $noteFields );
}
function updatingStock( $noteFields, $clientFields, $stockFields, $dbAction) {
global $wpdb;
printr($stockFields);
if ( $dbAction != 'update' ) {
foreach ( $stockFields['products'] as $product_id=>$stock ) {
$wpdb->query("UPDATE {$this->table_stock} SET stock=stock-{$stock} WHERE product_id='{$product_id}' AND location_id='{$stockFields['location_id']}'");
echo mysql_error()."<br />";
}
}
}
}
The main problem is action: saveNoteCommand who is executed twice on I press Save Command. The first execution is ok, but the second one generate error in MySQL ( duplicate key primary). I don't understand why wordpress executed twice a single function registered for an action, and I think this problem is generally in wordpress. All functions declared in this action is executed twice.
Can somebody help me to fix this, or to tell me if i wrong something
It's probably executing it twice because WP is saving two different posts, which in term is firing the action with your procedure twice:
the post in its new version as the post itself
the post in its old version as a revision
Assuming so, you need to check if the ID passed to whatever is calling your action is a revision or not.
my application doesnt have any relation with post in wordpress. Is in other directory, have other structure. The action saveNoteCommand is not executed on save_post / update_post. Is a custom action executed only in my script and only is $_POST data is submited.