Manually adding patterns like affiliate product banners, call-to-action, or any other type of reusable content to every post can be tedious and time-consuming.
The code we’ll discuss today allows you to dynamically insert any patterns at specific positions within your posts, providing even greater flexibility and automation.

Auto Insert Blocks In All Posts without plugins

By following these steps, you can easily incorporate dynamic insertion of reusable blocks or patterns into your WordPress posts.

Step 1: Create a pattern

  • In your WordPress admin dashboard, navigate to Appearance Patterns .
  • Create a new pattern by adding your desired blocks (e.g., an affiliate product banner, a call-to-action section, or any other recurring content).
  • Save the pattern and note down its ID.

Step 2: Add the Code to Your WordPress Site

Access your WordPress dashboard and navigate to Appearance Theme File Editor. Locate the functions.php file of your active theme and paste the following code snippet:

You must create a child theme before making any changes to functions.php file. Otherwise, the applied changes will be lost after each update.
Create child theme in WordPress step by step [without plugin]

As an alternative method, you can use the Code Snippets plugin to insert your codes into WordPress.

/**
 * Auto Insert Block In All Posts code by WPCookie
 * https://redpishi.com/wordpress-tutorials/auto-insert-content-in-all-posts/
 */
function add_message_after_third_block($block_content, $block) {
    $pattern_id = "000";
	$blocks = 5;
		
	static $block_count = 0;
    if ($block['blockName'] && $block_count < $blocks + 1 ) {
        $block_count++;
        if ($block_count === $blocks) {
            $message = get_post_field('post_content', $pattern_id);
            return $block_content . $message;
        }
    }
    return $block_content;
}
function add_filter_for_message($post) {
    if (is_singular('post') && in_the_loop()) {
        add_filter('render_block', 'add_message_after_third_block', 10, 2);
    }
}
add_action('the_post', 'add_filter_for_message');

Step 3: Customize the Code

  • Replace $pattern_id = "000"; with the ID of your reusable block or pattern.
  • Adjust the value of $blocks = 5; to specify the number of blocks after which the reusable block or pattern should be inserted. For example, setting it to 3 will insert the reusable content after the third block in your posts.

That’s it! Now, whenever you create or edit a post using the Gutenberg block editor, the specified pattern will automatically be inserted after the number of blocks you’ve set.

How the code works

The provided code utilizes the render_block filter in WordPress, which allows modifying the content of individual blocks within the Gutenberg editor. Here’s a brief explanation of how the code works:

  1. The add_message_after_third_block function is the main logic that handles the insertion of the reusable block or pattern.
  2. Inside this function, a static variable $block_count keeps track of the current block count.
  3. For each valid block encountered, the $block_count is incremented.
  4. When the $block_count matches the specified number of blocks ($blocks), the function retrieves the content of the reusable block or pattern using get_post_field('post_content', $pattern_id) and appends it to the current block content.
  5. The add_filter_for_message function checks if the current page is a singular post and if it’s in the main loop.
  6. If the conditions are met, it adds the add_message_after_third_block function as a filter to the render_block hook.
  7. The add_action function hooks the add_filter_for_message function to the the_post hook, ensuring that the filter is applied at the appropriate time during post rendering.

If this article is difficult for you to read in text, you can watch the video version below.

Share this post
Maya
Maya

Hi, my name is Maya and I’m a WordPress plugin developer. I created this website to share some of the helpful codes that I’ve used in my own projects.
If you’re looking for a custom plugin for your website, you can contact me by clicking on Hire a developer in the menu. I’d love to hear from you.

Articles: 57

2 Comments

    • The code provided in the tutorial should work for both desktop and mobile versions of your site, as it\’s applied on the server-side and should be platform-agnostic.
      However, there might be a few reasons why you\’re not seeing the changes on mobile:
      Caching: Your mobile device or a caching plugin might be serving an older version of the page. Try clearing your mobile browser\’s cache or disabling any caching plugins to see if the issue persists.
      Separate templates: If your theme uses separate templates for mobile and desktop, ensure that you\’ve applied the code modifications to the correct template files for mobile views.
      Theme/plugin conflicts: Check if there are any theme or plugin conflicts that might be affecting the code\’s functionality on mobile devices. Try disabling plugins one by one and switching to a default theme to identify potential conflicts.
      User agent detection: It\’s possible that your theme or a plugin is using user agent detection to serve different content for mobile and desktop. If this is the case, the code might need further modifications to handle different user agents.

Leave a Reply

Your email address will not be published. Required fields are marked *