Archived topic
Individual Hook
6 replies · Started by Sebastian on November 23, 2022
Hello,
I would like to add an affiliate banner notice right before my table of contents. I use the Table of Conents plugin for this.
How can I set my Blook Hook to show the element right before the table of contents?
Thanks
Hi Sebastian,
That's not possible unfortunately. It's not possible to create a hook inside the content section.
Sorry about that!
Ok, any other ideas how to do this?
Maybe "On every post before first H2"?
Hi Sebastian,
You can add a portable hook instead. See my response here: https://generatepress.com/forums/topic/hooks-related-question/#post-2170615
Doing so should allow you to add hooks in most locations.
Or are you looking to add it to every post before the first H2? If so, add this PHP snippet instead:
add_shortcode('portable_hook', function($atts){
ob_start();
$atts = shortcode_atts( array(
'hook_name' => 'no foo'
), $atts, 'portable_hook' );
do_action($atts['hook_name']);
return ob_get_clean();
});
add_filter( 'the_content', 'insert_custom_block', 20 );
function insert_custom_block( $content ) {
global $post;
$inserted_hook = do_shortcode('[portable_hook hook_name="before_first_h2"]');
if ( is_single() && ! is_admin() ) {
return prefix_insert_before_h2( $inserted_hook, 1, $content );
}
return $content;
}
function prefix_insert_before_h2( $insertion, $paragraph_id, $content ) {
$pattern = '/<h2/';
$replacement = $insertion . '<h2';
if( strpos($content, '<h2') !== false ) {
return preg_replace( $pattern , $replacement, $content, 1);
}
return $content;
}
Then, you can now use custom hook before_first_h2
Example: https://share.getcloudapp.com/v1uEvrwZ
Adding PHP: https://docs.generatepress.com/article/adding-php/#code-snippets
Thanks :)
You're welcome, Sebastian! :)