Embedding code in your WordPress posts

When adding code to a WordPress post, you may find that it gets modified (particularly when using the visual editor). For some years now, a popular plugin of mine, Code Embed, has allowed you a way to achieve this without any such modification. However, the plugin has had many features to it, making it a lot larger from what it first was. And that first release did it just a few lines of code.

So, dusting those lines down, bringing them up to VIP coding standards, here they are for anybody to easily add to their site, for example, via their functions.php theme file…

<?php
function embed_code( $content ) {
global $post;
$i = 1;
while ( $i < 6 ) {
$code = 'CODE' . $i;
$html = get_post_meta( $post->ID, $code, false );
$content = str_replace( '{{' . $code . '}}', $html[0], $content );
$i++;
}
return $content;
}
add_filter( 'the_content', 'embed_code' );
view raw code-embed.php hosted with ❤ by GitHub

How to use?

  • Head to the custom fields meta box on your posts page and add a new field.
  • Specify the field name as CODEx, where x is a number between 1 and 5 to uniquely identify that code for this post (therefore allowing up to 5 pieces of code to be inserted per post – there’s no reason you can’t expand this number, but I’ve get it to 5 for now).
  • The field value should be the code that you wish to embed in your post.
  • Once the custom field is saved, in your post simply write {{CODEx}} wherever you wish the code to appear (again, replace x with the relevant number).

2 responses

  1. I need help I have a wordpress website hosted on AWS. I need an automated way to convert a “Dynamic Lists” of youtube videos into embeddable links for wordpress. So I can make other lists in my wordpress site which uses the “snax open list” plugin and it has an automated browser extension that helps create and populate the snax lists and dynamic lists. Please check it out https://www.internettop40.com Please help my name is David Russell Ellenberger message me on the site “top40” or email me at info@internettop40.com

  2. Hello,

    I’m sure you get a ton of spammy submissions so I’ll get straight to the point – I’d love to submit a guest post or sponsored post for publishing on your site.

    The article is related to your website’s content, and of course, it’s useful and informative, I think your audience would positively love. 😃

    If you accept sponsored or guest post on your site, please let me know price for publishing a post on your website.

    Thanks for your time!

    Regards,
    Futing

Leave a Reply to David Russell EllenbergerCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from David Artiss

Subscribe now to keep reading and get access to the full archive.

Continue reading