Site logo

Archived topic

Block Element and Shortcode

5 replies · Started by _blank on November 6, 2021

Viewing posts 1–6 of 6

Hi,

I am trying to create a block element to replace the sidebar. Inside the element I wanted to include a side navigation shortcode (based on simple wp_list_pages listing). The layout is on the following screen:
https://1drv.ms/u/s!Ajkoo-gGVQk2iL0i02lKj83SFuwWRQ?e=JXW9Z9
(apart from the navigation shortcode there is a paragraph just to make the element visible in the sidebar; the container has red background to indicate where I would expect the shortcode output)

However, the navigation shows outside of the container where the shortcode is actually placed. Please check the following screen:
https://1drv.ms/u/s!Ajkoo-gGVQk2iL0hJA9OVeVvjgxUXw?e=A7pKIc
(the navigation from the shortcode has side-navigation class)

How to include in inside the container?

I used GenerateBlock container here but I'm not sure if the issue is related directly to GB, so I am posting here.

Thanks.

Hi there,

this is generally related to how the Shortcode is returning its data.
Can you share the code you used to create the Shortcode ?

Sure. That's the code to create a shortcode:


function side_navigation( $atts, $content = null ) {
	$post = get_post();
	echo '<ul class="side-navigation">';
	if ( is_page() && 0 === $post->post_parent ) {
		wp_list_pages( array(
			'child_of' => $post->ID,
			'title_li' => '',
		) );
	} elseif ( is_page() && 0 < $post->post_parent ) {
		$parents = get_post_ancestors( $post->ID );
		$top_level_parent_id = ( $parents ) ? $parents[ count( $parents ) - 1 ] : $post->ID;
		$top_level_parent = get_post( $top_level_parent_id );
		wp_list_pages( array(
			'child_of' => $top_level_parent->ID,
			'title_li' => '',
		) );
	}
	echo '</ul>';
}
add_shortcode( 'sidenavigation', 'side_navigation' );

Shortcodes should return their content not echo them as this will just get dumped into the content.
To get round that use output buffering like so:

function side_navigation( $atts, $content = null ) {

    ob_start();

    $post = get_post();
    echo '<ul class="side-navigation">';
    if ( is_page() && 0 === $post->post_parent ) {
        wp_list_pages( array(
            'child_of' => $post->ID,
            'title_li' => '',
        ) );
    } elseif ( is_page() && 0 < $post->post_parent ) {
        $parents = get_post_ancestors( $post->ID );
        $top_level_parent_id = ( $parents ) ? $parents[ count( $parents ) - 1 ] : $post->ID;
        $top_level_parent = get_post( $top_level_parent_id );
        wp_list_pages( array(
            'child_of' => $top_level_parent->ID,
            'title_li' => '',
        ) );
    }
    echo '</ul>';

    return ob_get_clean();

}
add_shortcode( 'sidenavigation', 'side_navigation' );

Yes, that worked :)
Thanks!

Glad to hear that

This archived topic is closed to new replies.