Safe And Useful Code Snippets

The Code Snippets add-on is probably the most under appreciated feature in the ManageWP arsenal. If you know how to use it, there’s virtually no limit to the ways you can put it to good use. But, what if you’ve never used code snippets before? I’ve put together a list of basic code snippets that you can play with and get familiar with the add-on. They are read only and can’t harm your server or website in any way, so don’t be afraid to try them!

 

code-snippet-featured

List Files

This snippet will list files in your root folder or if you set the folder path it would list files from a specific one.

echo `du -sch ./*`;
echo `ls -la ./wp-content/managewp/*`;

File Content

File content snippet will reveal an entire content of a specific file, you can easily change the path and the filename and you are done.

echo `cat ./wp-config.php`;

Time To Load Page

This snippet will print the loading time of the website’s home page.

$start = time();
// put a long operation in here
sleep(2);
$diff = time() - $start;
print "This page needed $diff seconds to load :-)";

Check File Size

You can easily check the size of any file on your server by running this snippet and all you need to do is to set the correct path and filename.

$filename = 'EXAMPLE/EXAMPLE.JPG';
echo $filename . ': ' . filesize($filename) . ' bytes';

Check Free Space on Your Server

Very useful snippet that will save you a lot of time needed for logging into your cPanel since you don’t have to leave ManageWP to check the free space on your server.

$bytes = disk_free_space(".");
$si_prefix = array( 'B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB' );
$base = 1024;
$class = min((int)log($bytes , $base) , count($si_prefix) - 1);
echo $bytes . '<br />';
echo sprintf('%1.2f' , $bytes / pow($base,$class)) . ' ' . $si_prefix[$class] . '<br />';

Check File Readability

By using this snippet, you will be able to see if the file on your server is readable or not.

$filename = 'FILENAME.EXTENSION';
if (is_readable($filename)) {
echo 'The file is readable';
} else {
echo 'The file is not readable';
}

Check Database Stats

This snippet will print out the Database statistics, just replace default values with the real ones.

$link = mysql_connect('HOST', 'USERNAME', 'PASSWORD');
$status = explode(' ', mysql_stat($link));
print_r($status);

Get Database Size

If you are using our Backup add-on, it might be redundant to use this snippet, but if you aren’t, you can check the database size by using this simple snippet.

$link = mysql_connect('host', 'username', 'password');

$db_name = "your database name here";
$tables = array();

mysql_select_db($db_name, $link);
$result = mysql_query("SHOW TABLE STATUS");

while($row = mysql_fetch_array($result)) {
/* We return the size in Kilobytes */
$total_size = ($row[ "Data_length" ] +
$row[ "Index_length" ]) / 1024;
$tables[$row['Name']] = sprintf("%.2f", $total_size);
}

print_r($tables);

That’s It Folks!

Please note that we have selected only the snippets that can’t harm your server and you can try them out with the knowledge that nothing will go wrong. Hopefully these snippets will help you in your daily work tasks. These are just some of our suggestions, but we are sure you have plenty of cool snippets up your sleeves. Share them with us, and let’s make the public snippet library a ton richer!

Aleksandar Savković

I believe that BIO should be seen as an ongoing process. Rather than a static snapshot, whereby we are perpetually re-framing, re-thinking and re-considering ourselves. So I reconsidered my profession and from the construction site supervisor, I became Web ” WordPress” developer in the age of 35. I believe that I’ll stick with this profession since I’m in love with WordPress for life.

20 Comments

  1. David Bartholomew

    Would you have a snippet that can review WooCommerce Orders to just display a count of orders for a period of time. Or just pull a list of order numbers, total$, order date, and order status?

    We have a lot of sites that operate with commissions that require us to open the site every week or month and this would be excellent if we could do via a snippet.

  2. keenan

    Hello,

    I am using fastest cache on all my sites.

    Could this code snippets me used to trigger a clear cache on all sites?

  3. Thomas Tremain

    Your database snippets are using the depricated mysql_* commands. You should be using $wpdb instead.

  4. Nathan

    Hi Aleksandar,
    This is such a great feature that we are jumping into using a lot more, along with a lot of other MWP features.
    As an agency we would love to run a script for installing a default set of plugins that we use regularly. I know for new sites that can be accomplished in a Template, but for existing sites it would be great. Would that be possible? Could you point me in the right direction for something like that?

  5. Gavin

    I am using fastest cache on all my sites. Could this code snippets me used to trigger a clear cache on all sites?
    also i use wpsweep on all site could i use this to to a sweep all on all sites?

    How would i find the codes if this can be done?

  6. Andy Warren

    I read or saw somewhere while looking into the code snippets functionality that you could sync plugin settings across sites with it, but it didn’t provide actual snippet needed to do so. Would you be able to point me in the right direction for that? Thanks!

  7. managewp

    Could you give an example showing how to list the titles of all custom posts? For example, in each website I have a knowledgebase which has a custom Post Type called “article” and would like to list all of the titles of these Articles. (You used to have a feature in the old version of ManageWP that would let me bulk-post Posts to multiple websites from the ManageWP Dashboard, I think, so this is sort of where I am headed; I would like to gather up the KB of all of my websites into one grand master KB… so I think if I could get the Titles then I could also get the content as well…)

    1. Aleksandar Savković

      Author

      Hello 🙂

      You can try to use this snippet for bulk posting but you will need a bit of technical knowledge.

      if ( ! function_exists( 'PostCreator' ) ) {

      function PostCreator(
      $name = 'AUTO POST',
      $type = 'post',
      $content = 'DUMMY CONTENT',
      $category = array(1,2),
      $template = NULL,
      $author_id = '1',
      $status = 'publish'
      ) {

      define( POST_NAME, $name );
      define( POST_TYPE, $type );
      define( POST_CONTENT, $content );
      define( POST_CATEGORY, $category );
      define( POST_TEMPLATE, '' );
      define( POST_AUTH_ID, $author_id );
      define( POST_STATUS, $status );

      if ( $type == 'page' ) {
      $post = get_page_by_title( POST_NAME, 'OBJECT', $type );
      $post_id = $post->ID;
      $post_data = get_page( $post_id );
      define( POST_TEMPLATE, $template );
      } else {
      $post = get_page_by_title( POST_NAME, 'OBJECT', $type );
      $post_id = $post->ID;
      $post_data = get_post( $post_id );
      }

      function hbt_create_post() {
      $post_data = array(
      'post_title' => wp_strip_all_tags( POST_NAME ),
      'post_content' => POST_CONTENT,
      'post_status' => POST_STATUS,
      'post_type' => POST_TYPE,
      'post_author' => POST_AUTH_ID,
      'post_category' => POST_CATEGORY,
      'page_template' => POST_TEMPLATE
      );
      wp_insert_post( $post_data, $error_obj );
      }

      if ( ! isset( $post ) ) {
      add_action( 'admin_init', 'hbt_create_post' );
      return $error_obj;
      }

      }
      }

      /* All available options for PostCreator()

      PostCreator( 'TITLE' , 'POST TYPE' , 'POST CONTENT' , 'POST CATEGORY' , 'TEMPLATE FILE NAME' , 'AUTHOR ID NUMBER' , 'POST STATUS');

      TITLE - HTML Stripped Out. Simple String.
      POST TYPE - Post type slug. Eg 'post' or 'page'. Custom Post Types are supported.
      POST CONTENT - Content of the Post/Page. HTML allowed.
      POST CATEGORY - An array of the integer ID's of the category/categories you want to link to your post
      TEMPLATE FILE NAME - File name of the template. Only for Pages. In the format 'file_name.php'.
      AUTHOR ID NUMBER - Integer value. Default is 1.
      POST STATUS - Available options; [ 'draft' | 'publish' | 'pending'| 'future' | 'private' | custom registered status ]

      If successful, PostCreator() returns nothing.
      If there is an error PostCreator() returns a WP_error object.

      */

      PostCreator( 'My Lorem Ipsum', 'page', 'With a sizable serving of Dolor. This was created using Harri Bell-Thomas\'s PostCreator function.' );

      Please let me know if this helped.

  8. Carlos

    I have 30 websites using the identical theme and layout. The only thing different is the content. I need to update the layout on each site. Is there a way for that to be done? In other words, I need to rearrange paragraphs and images to different places, but identical on each site.

    1. Aleksandar Savković

      Author

      Hmmm, to be honest Carlos I never even tried something like that and I don’t think it is possible with some simple snippet due to the fact that it is needed to change a lot of things. However, it might be helpful if the content is the same on every website to use our clone tool. Please note that clone tool will create an exact website copy so if some content is different that will not be a good solution, clone is a tool just for making an exact website on another server/domain. You can make changes on one website, make a backup and use that backup as a source for cloning. ” One more time, this is good and helpful but only if all websites are same and have the same content, images etc. “

  9. ral

    Hello Aleksander, I am a new user, I do not have access to the old classic wp. I am looking for a code snippet to clean up a site,
    which has inserted hidden links ( buyviagra, buypills.. etc..) , a code was mentioned in this article https://managewp.com/clean-link-injections-hacked-websites
    but I can not find it. please can you provide it

    Best Regards,

    Ral

    1. Aleksandar Savković

      Author

      Hi Ral,

      I sent you a snippet directly to your registered e-mail and I really hope that it helped 🙂

  10. David

    How does one use code snippets to change, for example, attributes in WP? For example if I wanted to use a code snippet to turn on or off “Discourage search engines” how would I do that. Also, can a code snippet change an attribute of a plug in? Again, turning on or off something?

    1. Aleksandar Savković

      Author

      Hi David,

      All snippets that I published are for the actions that you can’t do directly from ManageWP dashboard, turning on/off plugins is easy from the dashboard and I must say that it’s safer to use our add-on for that.

      Regarding discouraging search engines, it is doable by editing the Theme’s header.php file and changing the following line to:

      meta name=”robots” content=”noindex,nofollow”

      The most useful function of the code snippet add-on is getting quick information from your server with no need for visiting cPanel and we are not recommending using it for hacks even the ones that can’t harm your website.

      Please let me know if you need any help.

  11. ellegaard

    Well, at least you should be able to find a lot of snippets in the old ManageWP! 🙂

    I’m still looking for a solution to one very specifik problem – I need a list of the names of all installed (activated) plugins. I have managed to get a list of all their folder names, but that not quite the same.

    I use it for updating the documentation for each website, so it would a great timesaver to just run the snippet and copy/paster the resulting list.

    Still, this is one of my favorit functions of Orion now. 😉

    1. Aleksandar Savković

      Author

      Hi Ellegard,

      I could not agree more on this 🙂

      There is a lot of snippets in ManageWP Classic but our new users are not able to visit the Classic dashboard so I will pick some snippets from Classic and add them into the library for Orion, if you have some favorites, please let me know.

      Thanks for helping and have a great weekend.

  12. Ian

    This is so rad! You’re right, I’ve definitely been under-utilizing this feature (aka. not using it at all ?). Thanks for the writeup and samples to try!

    Is there really a current public snippet library? That’d be pretty handy.

    1. Aleksandar Savković

      Author

      Hi Ian, thanks for the great feedback and I am really glad that you like this library. I am aware that most of our users are not using Code Snippets even though they are the very useful add-on.

      I will do my best to update this post and add more snippets or even to publish the new post and name it ” Code Snippets Library ” that can be updated with new snippets and of course every suggestion or snippet that you find useful feel free to send me and I will add it to the library immediately.

      Enjoy using ManageWP 🙂

      1. Thomas Tremain

        Where can I find this code snippet library?

        1. Nemanja Aleksic

          Unfortunately, we haven’t collected enough universally useful code snippets to warrant another article.

Leave a Reply

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

Over 65,000 WordPress professionals are already using ManageWP

Add as many websites as you want for free, no credit card required. Sign up and start saving time!

Have questions? Get in touch!

Over 65,000 WordPress professionals are already using ManageWP

Add as many websites as you want for free, no credit card required. Sign up and start saving time!



Have questions? Get in touch!

Over 65,000 WordPress professionals are already using ManageWP

Add as many websites as you want for free, no credit card required. Sign up and start saving time!



Have questions? Get in touch!

Over 65,000 WordPress professionals are already using ManageWP

Add as many websites as you want for free, no credit card required. Sign up and start saving time!



Have questions? Get in touch!