I\'m having problems finding the right hook to use for my plugin. I\'m trying to add a message to the top of each page by having my plugin add a function. What\'s the best h
Creating custom hook is really easy in WordPress.
in header.php
(or anywhere you may need a hook) locate:
<body <?php body_class(); ?>>
<div id="body-container">
and make it:
<body <?php body_class(); ?>>
<?php body_begin(); ?>
<div id="body-container">
That's our hook, now let's make it work.
In functions.php
add:
function body_begin() {
do_action('body_begin');
}
Now hook is ready to use, simply add any actions you need in functions.php
:
function my_function() {
/* php code goes here */
}
add_action('body_begin', 'my_function');
or JavaScript (tracking code etc - this is not the perfect way though, it is a better practice to load JavaScript from .js
files, but it is definitely better than adding JavaScript directly to template files):
function my_function() { ?>
<script>
<!-- JavaScript goes here --!>
</script>
<?php
}
add_action('body_begin', 'my_function');
I searched the internet for answers to the same question but found nothing. I figured out away to to work around it. My plugin infinite Ad Pay is based on this method.
You need two hooks wp_head and wp_footer hook
add_action( 'wp_head', 'my_buffer_holder_fxn');
function my_buffer_holder_fxn(){
ob_start()
}
function my_buffer_pour_out_fxn(){
$get_me_buffers = ob_get_clean();
$pattern ='/<[bB][oO][dD][yY]\s[A-Za-z]{2,5}[A-Za-z0-9 "_=\-\.]+>|<body>/';
ob_start();
if(preg_match($pattern, $get_me_buffers, $get_me_buffers_return)){
$d_new_body_plus =$get_me_buffers_return[0]."<div class='my_below_body_code'> This is below the body text or image or anything you want </div>";
echo preg_replace($pattern, $d_new_body_plus, $get_me_buffers);
}
ob_flush();
}
}
add_action( 'wp_footer', 'my_buffer_pour_out_fxn');
// You can also use the method above to place anything in other sections of WordPress
//No Javascript used
In this scenario, what i do is: Use Jquery to append or prepend things:
http://api.jquery.com/prepend/