Search code examples
phpwordpressshortcodeelementorwordpress-gutenberg

WordPress - Shortcode is not rendering content on Gutenberg pages


Platform users have the ability to post offers. These offers are displayed in a post table.

You can see the post table here - https://www.b2bmember.com/b2b-marketplace/

Post table is inserted with a shortcode: [posts_table]

There is a possibility to only display posts from a specific author by adding author="x" at the end (x= user id).

Example: [posts_table author="x"]

The goal is to display posts from each user on their profile page.

I need a solution where every user has a corresponding shortcode in their profile page automatically / programmatically.

To achieve this, I created a function that creates a shortcode which is the same post table shortcode but with the user/author id part at the end.

function authorid() {

$author_id = um_user('ID');
echo '[posts_table author="' . $author_id . '"]';
}

add_shortcode('user_offers', 'authorid');

This solution works when I add [user_offers] on a page that is built with Elementor page builder - a post table with corresponding author posts is successfully rendered.

However, It does not work if a page is built with Gutenberg. For Gutenberg pages it displays [posts_table author="1"], 1 = user id depending on a profile page. So, the post table shortcode is generated correctly but nothing is rendering.

See a screenshot: https://pasteboard.co/K1YR7F7.png

I have tried to replace echo with return, but that does not fix the issue.

Why does it not work for pages that are built with Gutenberg / WordPress block editor?


Solution

  • I actually noticed that your shortcode returns a shortcode tag ([posts_table]) instead of the shortcode output, so you should call do_shortcode() like so:

    return do_shortcode( '[posts_table author="' . $author_id . '"]' );
    

    If you don't do that, then the default behavior in Gutenberg is that the [posts_table] is returned as-is instead of being parsed (e.g. replaced with a table HTML).

    And despite that I don't use Elementor, the above code should work well in Elementor.

    And keep in mind, shortcodes should always return the output and not echo it; otherwise, you'll likely get problems like invalid JSON response in the REST API (which for example, would then result in a failure saving a post through Gutenberg which uses the REST API).