You should use this plugin to insert PHP code in a safe way!There are some way you can embed another PHP code in your website: by adding code snippet in functions.php, by making a WordPress plugin or using a plugin which allows you to make code snippets.
In this tutorial I will introduce you Woody ad snippets (aka Insert PHP) and why I chose this
Using Insert PHP
Woody ad snippets allows you to insert 6 types of snippet, in which:
- PHP snippet = Used for inserting PHP code. Can be used for registering functions, hooks, global variables, printing text. Virtual functions.php.
- Text snippet = Used for inserting formatted text. Can be used for inserting quotes, paragraphs, shortcodes from other plugins, tables, media files.
- Universal snippet = Used for inserting PHP, HTML, JS& CSS code. Can be used for inserting ads, analytics, embeds & other complex scenarios.
- CSS snippet = Used for inserting CSS. Can be used for inserting CSS styles.
- HTML snippet = Used for inserting HTML code. Can be used for inserting HMTL code.
In order to use PHP snippet, just make one, put your PHP code snippet there. For example. this is a code snippet I used to display my upcoming post (Post I will write but don’t have time for now…)
<?php // the query $all_posts = new WP_Query( array( 'post_type' => 'post', 'post_status' => 'draft', 'posts_per_page' => -1 ) ); if ( $all_posts->have_posts() ) : ?> <ul> <?php while ( $all_posts->have_posts() ) : $all_posts->the_post(); ?> <li><i class="fa fa-envelope-o" aria-hidden="true"></i> <?php the_title(); ?></a></li> <?php endwhile; ?> </ul> <?php else : ?> <p><?php _e( 'Sorry, no posts were found.' ); ?></p> <?php endif; ?> <?php wp_reset_postdata(); ?>
To execute code snippet, you have 2 choices:
You can select Run Everywhere, the code will be executed as page load everywhere. Select Where There is a Shortcode will run code snippet where you embed the shortcode only.
For this specific purpose to display a Coming Soon posts, I put shortcode in a Widget as in picture below
This is the result
Why I chose Insert PHP
There are some reasons why I chose Insert PHP over some others of its kind:
- You can make 6 different types of snippet.
- You can use variable, attribute in snippet
- You can safely return your site when something went wrong.
Even an experienced person can make mistakes, especially when we are playing with PHP. Insert PHP provides a way to rollback to our site as following steps:
- Go to the safe mode by this link: http://your-site-name.dev/wp-admin/?wbcr-php-snippets-safe-mode
- Edit the snippet in which you made a mistake (or delete it)
- Leave safe mode by clicking the link: http://your-site-name.dev/wp-admin/?wbcr-php-snippets-disable-safe-mode
Great, now you should not have any issues!