Home Office equipment Embed posts into a WordPress page. Executable php code in WordPress posts

Embed posts into a WordPress page. Executable php code in WordPress posts

There are situations when it is very convenient to use the full potential of the PHP programming language in the text when writing articles. We are talking about articles for WordPress.

Anyone who has tried to write any PHP code in a post in the hope that it will work knows that WordPress treats such code as plain text. However, sometimes it is convenient to run, for example, some kind of output loop directly in the text when writing an article, because the content of such an article will be updated dynamically. Another example would be the ability to call ready-made functions in a post, if necessary, or, for example, insert some PHP file into the text of a post using the php function require():

Require "my_script.php";

In general, the imagination here is limitless and the truth is that the inability to use php in the text of an article in some cases can become a real problem. Once upon a time I encountered such a problem, I solved it by taking and slightly modifying the code from some plugin (I don’t remember the name now).

So, to implement the ability to insert executable PHP scripts in the text of an article/post or static page, you need to add the following code to the theme’s functions.php file, which is probably painfully familiar to us:

## Executable PHP code in WordPress post content. ## PHP_code ## ## @version: 1.0 if("Executable PHP code in the content")( add_filter("the_content", "content_exec_php", 0); function content_exec_php($content)( return preg_replace_callback("/\(. +?)\[\/exec\]/s", "_content_exec_php", $content); ) function _content_exec_php($matches)( if(" off" === $matches)( return "\n\n<"."pre>". htmlspecialchars($matches) ."\n\n"; ) else ( eval("ob_start(); ($matches); \$exec_php_out = ob_get_clean();"); return $exec_php_out; ) ) )

After the code is added, it will be possible to use this type of construction in articles:

Php code

For example:

// Comment global $wp_version; echo "Current WP version: $wp_version";

To disable code execution, you can use the following construct. It will simply display the code, as if we had inserted the php code as text.

Php code

Important about protection

The thing to remember is that anyone can use this feature, which is a huge security hole because if anyone has access to write articles, they can easily do whatever they want with the site.

To protect yourself from the possible harmful consequences of this hack, you can do the following simple protection (what immediately came to my mind): enable the execution of the php code construct only if, for example, the post has any custom field or, Let's say the post was written at 00 minutes. Naturally, only you will know this trick in which the code will be executed and, accordingly, only you will have the opportunity to insert PHP code into the article.

This feature will help you remove a dozen unnecessary plugins that insert any simple data into the body of the post with the possibility of pre-processing. Let's say, insert an adsense block anywhere. Or the dollar exchange rate updated in real time. Or any value stored in the WP database or a third party table.

Sometimes you need to insert the current date right into the middle of the text. That is, the date is not at the time of publication of the post, but the current date from the reader’s point of view. Or any other changing information or piece of JS code without post-processing by the engine. Or something that needs to be recalculated every time the page is refreshed, and this something should be in the body of the post. Or... Well, I think you understand. :)

We will write a plugin! It is very simple and does not require any knowledge in creating WP plugins. Its only drawback is the lack of a “face” in the WP admin panel, that is, it would not be comme il faut to deliver one to some customers. But for your own needs the option is excellent.

In the /wp-content/plugins/ folder, create a file with some unique name, say, “insert-any-data-into-post.php”. First, we write a comment block, which WP will subsequently parse to describe the plugin in its admin panel. You can write any data you want, then connect the shortcode and write a simple function. All code:

In short, that's all. :) Inside the function, you can do any actions, receiving and processing any data. In the example above, when writing a design anywhere in a post, the current date will be displayed at the time the visitor viewed this post.

You can also input various parameters to this function. Let's say the code below expands our function and adds the ability to display not only the current date, but also yesterday/tomorrow, and also allows you to change the type of date.

Function give_me_date_handler ($atts) ( //from the array of attributes we make allowed variables and set default values, optional but convenient extract(shortcode_atts(array("type" => "yesterday,today,tomorrow", "format" => "short ,full"), $atts)); //let's sort out what date we need switch($type) ( case "tomorrow": $time = strtotime("+1 day"); break; case "yesterday": $time = strtotime("-1 day"); break; default: $time = time(); ) // iterate over the date type if ($format == "short") $date = date("d.m.Y", $time); else $date = date("r", $time); return $date; )

The variables for our function are set via a tag in the post like this:

Result of the tag written above: 08/21/2019

Screenshot from the post editing admin area:

Through the function, you can pull data from the database and return it; you can simply return JS code, wrapping it in ob_start() and ob_end_clean() for convenience. You can also create several shortcodes and, accordingly, several functions, thus placing in one file/plugin all the necessary “insertions” for use inside the body of the publication.

In general, a useful thing!

- 5.0 out of 5 based on 2 votes

In the previous article we looked at for our WordPress blog, and here we’ll look at how posts (notes) are added in WordPress.

There are two types of content in WordPress, posts or as they are also called notes and pages. Posts are dynamic content that, as a rule, constantly appears on a blog in certain sections.

As for pages, these are ordinary static pages, with which you can create, for example, a page about the author or a blog.

To create a post, go to the WordPress admin panel: “Posts” >> “Add New”.

As a result, a text editor will be loaded, using the tools of which you can format the text, just as you do in the MS Word editor.

1. In the field "Enter title", indicate the title of the post.

2. Using the panel "Load/Paste", you can download and insert the necessary images and media files into your post.

3. Using the “Visual” and “HTML” tabs, you can move on to editing HTML code or remain working in a visual environment.

4. Using the panel tools, you can format the text. By clicking on the corresponding icon, you will open an additional panel with very useful tools.

First add a post title, after you specify the title and place the cursor in the text field of the editor, a permanent link will be automatically generated under the title, which will be used for this post. We set up permanent links in the lesson: "".

Insert text.

If you prepare your texts in the MS Word editor, then do not copy them directly into the editor window, use the “Paste from Word” tool.

To do this, copy the text in Word, then go to the WordPress editor and click on the “Paste from Word” icon, then paste the text into the window that opens and click on the “Paste” button.

If you paste text from Word directly into the WordPress text editor, then behind the text you will copy a lot of unnecessary code responsible for formatting the text. As a result, you will increase the size of your page, plus the presence of a large amount of unnecessary code is not treated very well by search engines.

Insert an image into the text.

To insert an image into the text, place the cursor at the place in the text where you want to insert the image and click on the “Insert Image” icon:

As a result, a window will load with three tabs. Using the “From Computer” tab, you can download and insert any image located on your computer. Using the “From Site” tab, you can specify the path to an image that is already located on any site, and using the “File Library” tab, you can insert any image from the media library. The media library stores all the files that you have downloaded previously.

As an example, let's insert an image from a computer. To do this, click on the “Select files” button, select the desired image and click the “Open” button. As a result, the image will load. After the image is uploaded, a window will appear in front of you, using the tools of which you can set certain attributes of the image.

The “Title” field is required. You can fill out the remaining fields “Text”, “Signature” and “Description” as desired.

In the “Link” field you can set a link that will go to the image. By default, the link goes to the image, if you click on the “Link to post” button, then the link from the image will go to the post itself, if you click on the “No” button, then there will be no link.

In the “Alignment” item, you can set the position of the image on the page.

In the "Size" item, you can set the image size.

After specifying all the parameters, click on the “Insert into post” button and the image will be inserted.

Insert the "Next" tag.

Select the recording format.

Starting with WordPress version 3.X, post formats were introduced. Using formats, you can choose a specific type of post display. This feature allows template developers to create different types of posts depending on their needs. The template installed in WordPrees by default uses three post display formats:

Post formats can be selected in the panel to the right of the editor. Post formats are only available in WordPress themes version 3.X. A total of 10 post formats are supported, their availability depends on the theme you are using. When using one format or another, tag the corresponding class is set, with which a given post format can be given a specific design using CSS.

Recently one of our readers asked if there was a way to add content from a WordPress page to another page or post. In this article, we will show you how to insert content from one WordPress page into another post, page, or any custom post type.

First of all, you need to install and activate the Insert Pages plugin. After activation, simply go to the section Posts » Add new administrative panel of the site in order to see it in action.

If you're using a visual editor, you'll notice a new button in the menu called 'Insert Page'.

Clicking on it will bring up a pop-up window where you can select the page, post, or custom post type you want to add.

You can choose how to insert into a post/page by clicking on Options. By default, you can add a title, content, link, or choose a custom template. We will tell you more about custom templates later in the article.

After selecting a post/page, click on the button Insert Page. Plugin to add the shortcode required to display the post/page you have selected.

If you use a text editor to compose your posts, you can paste the shortcode manually. The shortcode options are quite simple.

The page parameter for the shortcode accepts the page slug or its ID. Please note that slug can be any type of post, not necessarily a page.

You can also specify the entry ID. We have already written about how to find out the ID of a post in WordPress.

Adding Custom Post Types to Blog Entries

Using WordPress, you can add any type of content by creating post types for different types of content.

The Insert Pages plugin allows you to add custom post types to pages and blog posts. For example, you can create a custom post type for an image gallery, and then use Insert Pages to add those galleries to your posts or pages.

In the same way, you can create custom post types for videos, portfolios, customer reviews, etc. to add them to posts/pages.

Using custom templates to display inserted pages

Insert Pages allows you to display the title, link, content, or all fields for inserted pages. However, some users may need more fine-tuned output settings. This can be achieved by using custom templates.

All you need to do is create an empty php file and upload it to your theme folder. The file can be named whatever you like. For example, custom-author.php.

This custom template works exactly like any other content template file in your theme. Below is an example of the template file we created to display author pages.

You can use custom CSS classes in your template file and then apply styles in the theme's stylesheet file. We used the following code to design the author page.

H3.author-name ( font-size:16px; ) .author-thumbnail ( float:left; padding:10px; ) .author-bio ( font-style:italic; font-family: Lora, Georgia, Serif; )

This is what the final version looks like:

We hope this article helped you add content from one WordPress page/post to another.

If you need to insert pieces of code into posts or pages on a WordPress website, then our post today will be useful to you. This can be useful, for example, when you publish programming tutorials and need to insert small code snippets into your posts as a sample. After all, it is very often necessary to show your readers source code samples in PHP, JavaScript, CSS or any other programming language.

By default, WordPress filters any raw code added to posts, pages, widgets, or comments. This is done for security purposes so that the program code is not executable. If, for example, you first write a post in Word or any text editor, and then paste this text into the post edit field in the WordPress console, the engine will automatically convert some characters. For example, the symbol< в режиме просмотра Текст будет преобразован в < . Т.е., если вы вставляете в Визуальном режиме, например, фрагмент кода, который начинается с

In fact, the same result will happen if you do not paste the source text, but write it directly in the Visual Editor mode. But, if you write code directly in Text mode, then the system, again for security reasons, will comment out your code, and will remove some special characters altogether.

Try, for example, writing in Text mode:

When you switch to Visual mode (or after publishing a post), you will not see the desired text Hello, World! because the system hid it so that it would not be executable. This is where we come to the problem: how to display program code in WordPress posts?

An Easy Way to Display Code in WordPress

The easiest way to add code to your posts is to wrap the program code in Text mode with an HTML tag

This tag is intended to display the code as it was printed, i.e., with all spaces, special characters, and the like.  It would be possible, of course, not to use this tag, but to write all the program code at once using HTML entities, but this is a very complex approach.  It’s much easier to write the necessary code in the Visual mode of editing a publication, and then switch to Text mode and frame the desired fragment with tags 
........
, and at the same time all “dangerous” programming characters are automatically converted into HTML entities.

For example, the above code in Text mode would look like this:

Tag

is an ideal element for large blocks of code because it allows you to preserve all spaces, tabs, and the like.

For small blocks of code, you can use an HTML5 tag specifically designed for code - . In the Text editing mode in WordPress there is even a special shortcode for this. When editing a post, select the desired fragment and click the code button on the toolbar, and this fragment will be framed with tags ........ .

Tag

- block, and tag — inline, i.e., most browsers display it as display: inline;  and it can be shown directly in the paragraph, and not on a new line.

A Complicated Way to Display Code in WordPress

As a complex way of displaying program code, I include special plugins for this (for example, Crayon Syntax Highlighter, Syntax Highlighter Evolved and the like). Someone might argue that this is, on the contrary, a simple method, but I believe that all sorts of fancy plugins only complicate everything. Very often you can find a situation on websites when previously designed code using plugin shortcodes is still displayed in the browser after a while, for example:

but there should be a beautiful design and syntax highlighting. Very often, such plugins are not compatible with new versions of the engine, or webmasters often forget to update them. Or worse, they use several of these plugins at once.

Yes, such plugins very nicely do syntax highlighting on the fly using JavaScript and CSS, but they are mostly quite “heavy” for the system, and basic syntax highlighting can be done without plugins, using several classes for div, span, code and pre tags , as well as several lines of CSS styles.

The choice is yours!

And I would like to include the use of third-party services as a complex method of inserting code into WordPress pages. There are quite a few sites where you can write almost any code and it will display as it should. Examples of such services: CodePen, GitHub Gists and JSFiddle.

They provide very nice syntax highlighting and even a demo view of the result of code execution, but their complexity lies in the need to use iframes or external JavaScript libraries for insertion. I use this method only to show a demo of the result of code execution.

Conclusion

As you can see, adding code to a WordPress site is not such a difficult task, but you still need to know the basic solutions for this.

If you have any other solutions for adding code to WordPress posts/pages, please let us know in the comments below.

New on the site

>

Most popular