Introduction
Sometimes we need to use small snips of code to accomplish certain functionalities because it is either the only option or it’s a cleaner approach than other methods. This is often done by adding code to our active themes functions.php
file, which is essentially a theme-specific plugin file. Code is only executed here if the theme is active or a child theme that relies on it is active.
Many of these code snips rely on placement in your active themes functions.php
file or another file directly referenced by it via a require() or require_once() PHP function, some are commands to be run in Linux, Unix or Mac OSX. Most of these code snips can also be placed in your custom plugins. If you are not sure what you’re doing, placing these code snips at the end of your active themes functions.php
is your best bet for success, placing the code anywhere else in the file could lead to errors or incorrect/unwanted results. Make sure to remove any closing PHP tags ?>
on the last line of your functions.php
, they’re unneeded.
IMPORTANT: Before making any code changes, backup all files and databases.
Create an administrator account with only s/FTP or ssh access to your WordPress site
Description
Accidents happen, passwords are lost or forgotten or sometimes we’re given a site to work on with insufficient access or the client is unaware of how to give more access. The code below will allow us to create a new admin user with only access to FTP or ssh.
How to Implement
- Login to the DocumentRoot of the website
- Navigate to
/wp-content/themes/your_active_theme/functions.php
and download this file locally - Make a backup of this file in another local directory
- Open
functions.php
in a text editor and scroll to the bottom, make sure to remove any closing PHP bracket?>
- Add the code below to the bottom of
functions.php
- Upload and overwrite/replace the
functions.php
with the one we just edited - Reload the main website, this will run the code the
functions.php
- Login with the new credentials: https://example.com/wp-login.php
- After successful, replace the
functions.php
with the backup we make in Step 3 above
Example Code:
1 2 3 4 5 6 7 8 9 10 11 12 | //Edit: username, password, user@example.com function admin_account(){ $user = 'username'; $pass = 'password'; $email = 'user@example.com'; if ( !username_exists( $user ) && !email_exists( $email ) ) { $user_id = wp_create_user( $user, $pass, $email ); $user = new WP_User( $user_id ); $user->set_role( 'administrator' ); } } add_action('init','admin_account'); |
Disable stripping elements in TinyMCE when switching from text to visual mode
Description
The WordPress post/page visual editor (TinyMCE) strips out various HTML tags and attributes that are seen as unhelpful, bad practice or security risks such as: iframe, some table style properties, and other HTML attributes. The code and steps below will disable this filter, allowing you to use these.
How to Implement
- Login to the DocumentRoot of the website
- Navigate to
/wp-content/themes/your_active_theme/functions.php
and download this file locally - Make a backup of this file in another local directory
- Open
functions.php
in a text editor and scroll to the bottom, make sure to remove any closing PHP bracket?>
- Add the code below to the bottom of
functions.php
- Upload and overwrite/replace the
functions.php
with the one we just edited - Reload the main website, this will run the code the
functions.php
- Login, go to the page or post edit screen and test by pasting code with a previously stripped HTML tag and switch between the text and visual editor tabs
Example Code:
1 2 3 4 5 | function mod_mce($initArray) { $initArray['verify_html'] = false; return $initArray; } add_filter('tiny_mce_before_init', 'mod_mce'); |
Auto-update specific plugins only
Description
If you have the need to make sure certain plugins are always kept up to date, or to make sure others are not updated automatically, you can define them in this code snip below. In our example we’re using Akismet and BuddyPress as the plugins we’d like to keep up to date as soon as there’s a new release.
How to Implement
- Login to the DocumentRoot of the website
- Navigate to
/wp-content/themes/your_active_theme/functions.php
and download this file locally - Make a backup of this file in another local directory
- Open
functions.php
in a text editor and scroll to the bottom, make sure to remove any closing PHP bracket?>
- Add the code below to the bottom of
functions.php
- Upload and overwrite/replace the
functions.php
with the one we just edited - Reload the main website, this will run the code the
functions.php
- It’s best to test this when you know for a fact there is an update to a specific plugin you want kept up to date, otherwise you’ll be waiting until there is.
Example Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 | function auto_update_specific_plugins ( $update, $item ) { // Array of plugin slugs to always auto-update $plugins = array ( 'akismet', 'buddypress', ); if ( in_array( $item->slug, $plugins ) ) { return true; // Always update plugins in this array } else { return $update; // Else, use the normal API response to decide whether to update or not } } add_filter( 'auto_update_plugin', 'auto_update_specific_plugins', 10, 2 ); |
Locate base64-encoded content within your WordPress DocumentRoot
Description
Often, people seeking to do your site harm with infect it with base64-encoded PHP which obfuscates the true purpose and intent of the code.
How to Implement
- Copy the code into a file in the DocumentRoot of your WordPress install on your server and call it
base64-hunter.sh
- Once that’s done:
chmod +x base64-hunter.sh
- Next,
./base64-hunter.sh
then hit enter - You should be left with two files:
base64-detections.txt
&eval-detections.txt
- With this information you can isolate and clean infected files
- You can also simply copy each command and run them manually if you prefer
- Use
man find
&man grep
to learn more about what’s happening with these commands
Example Code:
1 2 3 | #!/bin/bash find . -name "*.php" -exec grep "base64" '{}' \; -print &> base64-detections.txt find . -name "*.php" -exec grep "eval" '{}' \; -print &> eval-detections.txt |
Hide WordPress page/post editor on specific pages or when using specific templates
Description
You may have the need to hide the page editor from unskilled editors on occasion only for certain pages, use the code below to do so.
- Login to the DocumentRoot of the website
- Navigate to
/wp-content/themes/your_active_theme/functions.php
and download this file locally - Make a backup of this file in another local directory
- Open
functions.php
in a text editor and scroll to the bottom, make sure to remove any closing PHP bracket?>
- Add the code below to the bottom of
functions.php
- Upload and overwrite/replace the
functions.php
with the one we just edited - Reload the main website, this will run the code the
functions.php
- Login and visit the post/page editor to verify the changes
Example Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <?php /** * Hide editor on specific pages. * */ add_action( 'admin_init', 'hide_editor' ); function hide_editor() { // Get the Post ID. $post_id = $_GET['post'] ? $_GET['post'] : $_POST['post_ID'] ; if( !isset( $post_id ) ) return; // Hide the editor on the page titled 'Homepage' $homepgname = get_the_title($post_id); if($homepgname == 'Homepage'){ remove_post_type_support('page', 'editor'); } // Hide the editor on a page with a specific page template // Get the name of the Page Template file. $template_file = get_post_meta($post_id, '_wp_page_template', true); if($template_file == 'my-page-template.php'){ // the filename of the page template remove_post_type_support('page', 'editor'); } } |
Linux server BASH backup script
Description
This script will backup your servers /etc, /var/log, /var/www, /var/lib/mysql as well as sync your time and timezone settings, provide detailed lists of installed software and backup pruning. This script was written for Red Hat Linux, Centos or Fedora in mind but can easily be adapted to your Linux distro by changing the relevant file and directory paths. Feel free to edit it and make it your own.
How to Implement
vi /root/serverbackup.sh
paste and edit script belowesc :wq
exit vichmod +x /root/serverbackup.sh
mark as executablevi /etc/cron.daily/serverbackup
paste the next line into this file (step 5)bash /root/serverbackup.sh > /dev/null 2>&1
this code will run once everydaychmod +x /etc/cron.daily/serverbackup
esc :wq
Testing
/root/./serverbackup.sh
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | #!/bin/bash #Server Backup ######################## ### Global Variables ### ######################## USER="username" DIR="sysbackup" DATE=`date +%d-%b-%Y-%a-%I:%M:%S-%p-%Z` SERVER=`uname -n` ########################################### ### Setting System Time, Date, Location ### ########################################### ### Reset System Timezone After tzdata Updates ### echo "Resetting System Timezone..." ln -sf /usr/share/zoneinfo/America/Los_Angeles /etc/localtime ### Sync System Time ### #echo "Setting System Time..." ntpdate pool.ntp.org ###################### ### Backup Pruning ### ###################### echo "Removing Stale Backups..." ### Delete any file or directory over 15 minutes old ### #find /home/$USER/$DIR/ -mmin +15 -exec rm -rf {} + ### Delete any file or directory over 15 days old ### #find /home/$USER/$DIR/ -mtime +15 -exec rm -rf {} + ### Delete all files and directories ### #echo "Removing Previous Backups..." #rm -rf /home/$USER/$DIR ##################################### ### Create Dated Backup Directory ### ##################################### echo "Starting System Backup for $SERVER..." mkdir -p /home/$USER/$DIR/$DATE ############################################### ### Backup Config, Databases, Logs, Webroot ### ############################################### ### System Configuration ### echo "Backing up $SERVER Configuration..." tar -cvzPf /home/$USER/$DIR/$DATE/$DATE-$SERVER-etc.tar.gz /etc ### System Log Files ### echo "Backing up $SERVER Logs..." tar -cvzPf /home/$USER/$DIR/$DATE/$DATE-$SERVER-logs.tar.gz /var/log echo "Backing up $SERVER DocumentRoots..." ### Individual DocumentRoots ### tar -cvzPf /home/$USER/$DIR/$DATE/$DATE-$SERVER-example.com.gz /var/www/example.com/ tar -cvzPf /home/$USER/$DIR/$DATE/$DATE-$SERVER-example.org.tar.gz /var/www/example.org/ ### All DocumentRoots ### tar -cvzPf /home/$USER/$DIR/$DATE/$DATE-$SERVER-www.tar.gz /var/www/ ### MySQL / MariaDB Backup ### echo "Dumping $SERVER MySQL Databases..." mysqldump --events -u backupdba -pSecurePassword --all-databases > /var/lib/mysql/all_databases.sql mysqldump --events -u backupdba -pSecurePassword example_database > /var/lib/mysql/example_database.sql echo "Backing up $SERVER MySQL Directories & Files..." tar -cvzPf /home/$USER/$DIR/$DATE/$DATE-$SERVER-mysql.tar.gz /var/lib/mysql ######################################### ### Installed RPMs & Yum Repos Backup ### ######################################### echo "Backing up $SERVER Installed RPMs & Yum Repos..." ### List of all installed RPM's ### rpm -qa --qf '%{name}-%{version}-%{release}\n' | sort -d > /home/$USER/$DIR/$DATE/rpmlist.txt ### List of all installed Yum Repositories ### yum repolist all > /home/$USER/$DIR/$DATE/repolist.txt ################################################ ### File & Directory Ownership / Permissions ### ################################################ echo "Changing File Ownership..." chown -Rf $USER:$USER /home/$USER/sysbackup echo "Changing File Permissions..." chmod -Rf 755 /home/$USER/sysbackup echo "$SERVER Backups Complete." |
Add sortable 'last modified' column for pages/posts in wp-admin
Add nice sortable column with last modified dates/times for posts and pages in the wp-admin post/page editor main screen.
- Login to the DocumentRoot of the website
- Navigate to
/wp-content/themes/your_active_theme/functions.php
and download this file locally - Make a backup of this file in another local directory
- Open
functions.php
in a text editor and scroll to the bottom, make sure to remove any closing PHP bracket?>
- Add the code below to the bottom of
functions.php
- Upload and overwrite/replace the
functions.php
with the one we just edited - Reload the main website, this will run the code the
functions.php
- Login and visit the post/page editor to verify the changes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | /*********************************************************************/ /* Add a sortable "Last Modified" column in wp-admin for pages/posts */ /*********************************************************************/ function heirch_columns( $column, $post_id ) { switch ( $column ) { case 'modified': $m_orig = get_post_field( 'post_modified', $post_id, 'raw' ); $m_stamp = strtotime( $m_orig ); $modified = date( get_option( 'date_format' ).' @ '.get_option( 'time_format' ), $m_stamp ); $modr_id = get_post_meta( $post_id, '_edit_last', true ); $auth_id = get_post_field( 'post_author', $post_id, 'raw' ); $user_id = !empty( $modr_id ) ? $modr_id : $auth_id; $user_info = get_userdata( $user_id ); echo '<p class="mod-date">'; echo '<em>'.$modified.'</em><br />'; echo 'by <strong>'.$user_info->display_name.'<strong>'; echo '</p>'; break; // end all case breaks } } function page_columns( $columns ) { $columns['modified'] = 'Last Modified'; return $columns; } add_action('manage_pages_custom_column', 'heirch_columns', 10, 2); add_filter('manage_edit-page_columns', 'page_columns'); function post_columns_data( $column, $post_id ) { switch ( $column ) { case 'modified': $m_orig = get_post_field( 'post_modified', $post_id, 'raw' ); $m_stamp = strtotime( $m_orig ); $modified = date( get_option( 'date_format' ).' @ '.get_option( 'time_format' ), $m_stamp ); $modr_id = get_post_meta( $post_id, '_edit_last', true ); $auth_id = get_post_field( 'post_author', $post_id, 'raw' ); $user_id = !empty( $modr_id ) ? $modr_id : $auth_id; $user_info = get_userdata( $user_id ); echo '<p class="mod-date">'; echo '<em>'.$modified.'</em><br />'; echo 'by <strong>'.$user_info->display_name.'<strong>'; echo '</p>'; break; // end all case breaks } } function post_columns_display( $columns ) { $columns['modified'] = 'Last Modified'; return $columns; } add_action('manage_posts_custom_column', 'post_columns_data', 10, 2); add_filter('manage_edit-post_columns', 'post_columns_display'); function last_modified_column_register_sortable( $columns ) { $columns["modified"] = "last_modified"; return $columns; } add_filter( "manage_edit-post_sortable_columns", "last_modified_column_register_sortable" ); add_filter( "manage_edit-page_sortable_columns", "last_modified_column_register_sortable" ); |
Use ImageMagick instead of PHP-GD for image uploads
1 2 3 4 | add_filter('wp_image_editors', 'force_imagick'); function force_imagick() { return array('WP_Image_Editor_Imagick'); } |
Remove WordPress Emoji's
Description
WordPress automatically converts some ASCII characters into Emoji’s which may interfere with your intended use, use the code below to remove this.
- Login to the DocumentRoot of the website
- Navigate to
/wp-content/themes/your_active_theme/functions.php
and download this file locally - Make a backup of this file in another local directory
- Open
functions.php
in a text editor and scroll to the bottom, make sure to remove any closing PHP bracket?>
- Add the code below to the bottom of
functions.php
- Upload and overwrite/replace the
functions.php
with the one we just edited - Reload the main website, this will run the code the
functions.php
- Login and visit the post/page editor to verify the changes
1 2 3 | // REMOVE EMOJI ICONS remove_action('wp_head', 'print_emoji_detection_script', 7); remove_action('wp_print_styles', 'print_emoji_styles'); |
Make Offline Mirror of a Site using wget
wget --mirror --convert-links --adjust-extension --page-requisites --no-parent http://example.org
Explanation of the various flags:
- –mirror – Makes (among other things) the download recursive.
- –convert-links – convert all the links (also to stuff like CSS stylesheets) to relative, so it will be suitable for offline viewing.
- –adjust-extension – Adds suitable extensions to filenames (html or css) depending on their content-type.
- –page-requisites – Download things like CSS style-sheets and images required to properly display the page offline.
- –no-parent – When recursing do not ascend to the parent directory. It useful for restricting the download to only a portion of the site.
Alternatively, the command above may be shortened:
wget -mkEpnp http://example.org
Note: that the last p is part of np (–no-parent) and hence you see p twice in the flags.
Also see: http://www.httrack.com/ website mirroring tool.
Add blasklisted mimtypes for upload into WP Media
Description
WordPress blocks certain mimetypes as “harmful” or security risks by default, use the working example code below to alter this behaviour, edit as needed.
- Login to the DocumentRoot of the website
- Navigate to
/wp-content/themes/your_active_theme/functions.php
and download this file locally - Make a backup of this file in another local directory
- Open
functions.php
in a text editor and scroll to the bottom, make sure to remove any closing PHP bracket?>
- Add the code below to the bottom of
functions.php
- Upload and overwrite/replace the
functions.php
with the one we just edited - Reload the main website, this will run the code the
functions.php
- Login and visit the post/page editor to verify the changes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function t4a_add_custom_upload_mimes($existing_mimes){ return array_merge($existing_mimes, array( 'csv' => 'application/octet-stream', 'xml' => 'application/atom+xml', '7z' => 'application/x-7z-compressed', 'rar' => 'package/rar', 'tar' => 'package/x-tar', 'tgz' => 'application/x-tar-gz', 'apk' => 'application/vnd.android.package-archive', 'zip' => 'package/zip', 'img|iso' => 'package/img', 'gz|gzip' => 'package/x-gzip', 'deb|rpm' => 'package/x-app', 'ttf|woff' => 'application/x-font') ); return $existing_mimes; } add_filter('upload_mimes', 't4a_add_custom_upload_mimes'); |
Limit Add to Cart to 1 product in WooCommerce
Description
This is useful for something like a membership or subscription site, where you’re selling only one of several choices. For example: Brone, Silver, Gold, etc. This function prevents users from adding 2 Silver account or 1 of each, etc, so they are only allowed to buy one membership level at a time, per user.
- Login to the DocumentRoot of the website
- Navigate to
/wp-content/themes/your_active_theme/functions.php
and download this file locally - Make a backup of this file in another local directory
- Open
functions.php
in a text editor and scroll to the bottom, make sure to remove any closing PHP bracket?>
- Add the code below to the bottom of
functions.php
- Upload and overwrite/replace the
functions.php
with the one we just edited - Reload the main website, this will run the code the
functions.php
- Login and visit the post/page editor to verify the changes
1 2 3 4 5 6 7 8 | function woo_check_empty_cart( $valid, $product_id, $quantity ) { if( ! empty ( WC()->cart->get_cart() ) && $valid ){ WC()->cart->empty_cart(); wc_add_notice( 'Whoa hold up. You can only have 1 membership in your cart', 'error' ); } return $valid; } add_filter( 'woocommerce_add_to_cart_validation', 'woo_check_empty_cart', 10, 3 ); |