[Resolved] Individual Hook

Home Forums Support [Resolved] Individual Hook

Home Forums Support Individual Hook

Viewing 7 posts - 1 through 7 (of 7 total)
  • Author
    Posts
  • #2429774
    Sebastian

    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

    #2429810
    Leo
    Staff
    Customer Support

    Hi Sebastian,

    That’s not possible unfortunately. It’s not possible to create a hook inside the content section.

    Sorry about that!

    #2429851
    Sebastian

    Ok, any other ideas how to do this?

    #2429858
    Sebastian

    Maybe “On every post before first H2”?

    #2430170
    Fernando
    Customer Support

    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

    #2441761
    Sebastian

    Thanks ๐Ÿ™‚

    #2443728
    Fernando
    Customer Support

    You’re welcome, Sebastian! ๐Ÿ™‚

Viewing 7 posts - 1 through 7 (of 7 total)
  • You must be logged in to reply to this topic.