[Support request] Customised elements

Home Forums Support [Support request] Customised elements

Home Forums Support Customised elements

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #2371563
    Javier

    Hi, I need to put a custom element that for example appears on all pages after the third paragraph, how can I do it?

    #2371591
    Ying
    Staff
    Customer Support

    Hi Javier,

    1. Try add this PHP code:

    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_element', 20 );
    function insert_element( $content ) {
        global $post;
        $inserted_hook = do_shortcode('[portable_hook hook_name="after_third_paragraph"]');
        if ( is_single() && ! is_admin() ) {
            return prefix_insert_after_paragraph( $inserted_hook, 3, $content );
        }
        return $content;
    }
    function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
      $closing_p = '</p>';
      $paragraphs = explode( $closing_p, $content );
      foreach ($paragraphs as $index => $paragraph) {
        if ( trim( $paragraph ) ) {
         $paragraphs[$index] .= $closing_p;
        }
        if ( $paragraph_id == $index + 1 ) {
         $paragraphs[$index] .= $insertion;
        }
      }
      return implode( '', $paragraphs );
    }

    Adding PHP: https://docs.generatepress.com/article/adding-php/

    2. Add your element to a block element – hook, choose custom hook, then enter after_third_paragraph as the hook name.
    https://www.screencast.com/t/DmLsa8EK

    #2372186
    Javier

    hello again, it seems that the code works but it is only shown in the blog entries, my intention is that the custom block can also be shown in the pages…. how can I do it?

    #2372509
    David
    Staff
    Customer Support

    Hi there,

    in the above code look for this line:

    if ( is_single() && ! is_admin() ) {

    and change it to:

    if ( ( is_single() || is_page() ) && ! is_admin() ) {

    #2372675
    Javier

    Perfect, now the block also appears on the pages.
    Thank you very much.

    #2373201
    David
    Staff
    Customer Support

    Glad to hear that!

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