If you’re using the classic editor, then a custom shortocode is a good option. Although shortcodes can be used with the block editor the more modern way would be to create a custom (dynamic) block.
You can insert the shortcode / block to the post content when needed and have the callback handle any necessary logic and rendering.
If you prefer, you could also use the_content filter, which lets you modify the post’s content, as a string, before it is rendered – assuming you’re using the_content() in your Loop or otherwise applying the filter to the post content.