Automatic Lossless Image Compression

We have a robot – his name is optimizerbot and he will look through your themes daily to find any PNG or JPEG images that can be losslessly compressed and automatically commit the compressed version to your theme’s subversion repository.   We have found that about 80% of existing images in VIP themes can be compressed this way, saving precious bytes and providing a better user experience, especially on slower networks, like 3G.

Here is an example of what the commit message will look like:

optimizerbot-commit

The first column is the file name, second column is the old file size in bytes, third column is the new file size in bytes, and the last column is the % saved.

Technical details for those who are interested:

  • PNGs are being compressed using OptiPNG.
  • JPEGs are being compressed using jpegoptim.
  • The script we are using to do the compression will soon be available in the WordPress Code SVN repository.
  • We invalidate our CDN whenever static content is changed which means users will begin downloading optimized versions of these files shortly after the changes are deployed.
  • For those familiar with Trac Wiki syntax you probably will recognize the || separator. This creates a table layout in Trac, which we use internally for reviewing changes in some cases.

Code Review: What We Look For

Every line of code that is committed to WordPress.com VIP is reviewed by the VIP Team. We don’t do in-depth code reviews to add more time to or delay your launch schedules. We do these lengthy code reviews to help you launch successfully.

The goal of our reviews is to make sure that on launch, your site will be:

  • Secure, because pushing a site live with insecure code presents a liability to you and your whole userbase;
  • Performant, because going live and finding out that your code can’t handle the traffic levels that your site expects puts most of your launch efforts to waste.

We also review for development best practices to make sure that your site will continue to live on without significant maintenance costs or major issues when WordPress is upgraded.

Before submitting any code for review, please be sure to look through our Code Review Guidelines and Best Practices Documentation. The following is a checklist of items our VIP engineers look for when reviewing. Please note that this is a living list and we are adding and modifying it as we continue to refine our processes and platform.

We also have more documentation on topics that come up often such as:

We hope that by sharing this document, you will be able to better prepare your code for peer review.


Blockers

Blockers are items that need to be fixed before being committed to WordPress.com. Here’s a partial list of what can be a blocker:

Direct Database Queries

Thanks to WordPress’ extensive API, you should almost never need to query database tables directly. Using WordPress APIs rather than rolling your own functions saves you time and assures compatibility with past and future versions of WordPress and PHP. It also makes code reviews go more smoothly because we know we can trust the APIs. More information.

Additionally, direct database queries bypass our internal caching. If absolutely necessary, you should evaluate the potential performance of these queries and add caching if needed.

Database alteration

The WordPress schema and API’s are roboust enough to handle almost any requirements. The core API’s are easy to use and add a performance layer to ensure that your site will run smoothly.

Creating or deleting tables, and schema modifications are not allowed. Themes and plugins should use the existing database tables and structure. Plugins which create custom database tables during installation cannot be used. We recommend finding an alternative that doesn’t use custom database tables or rewriting the plugin to use Custom Post Types, Custom Taxonomies, post meta, etc. — all of which are incredibly flexible as an alternative to custom database tables.

Filesystem writes

Make sure that your code and plugins do not write to the filesystem. Since the WordPress.com network is distributed across many servers in multiple data centers, file system writes won’t work how they would in a single server environment. The core WordPress upload functions can handle any uploads you need to do.

Validation, Sanitization, and Escaping

Your code works, but is it safe? When writing code for the WordPress.com VIP environment, you’ll need to be extra cautious of how you handle data coming into WordPress and how it’s presented to the end user. Please review our documentation on validating, sanitizing, and escaping.

$_GET, $_POST, $_REQUEST, $_SERVER and other data from untrusted sources (including values from the database such as post meta and options) need to be validated and sanitized as early as possible (for example when assigning a $_POST value to a local variable) and escaped as late as possible on output.

Nonces should be used to validate all form submissions. This includes parts in the code such as a save_post where the user’s intend has ostensibly already been verified since this code can be run in unexpected contexts, for example on the jobs servers, as a wp-cli command, as a syndication task or other task. In these cases it’s often a protection for the code to only be run when it was intended to run.

Capability checks using current_user_can() need to validate that users can take the requested actions.

It’s best to do the output escaping as late as possible, ideally as it’s being outputted, as opposed to further up in your script. This way you can always be sure that your data is properly escaped and you don’t need to remember if the variable has been previously validated.

Here are two examples. In order to keep this straight forward, we’ve kept them simple. Imagine a scenario with much more code between the place where $title is defined and where it’s used. The first example is more clear that $title is escaped.

$title = $instance['title'];

// Logic that sets up the widget

echo $before_title . esc_html( $title ) . $after_title;

 

$title = esc_html( $instance['title'] );

// Logic that sets up the widget

echo $before_title . $title . $after_title;

More information.

Arbitrary JavaScript and CSS stored in options or meta

To limit attack vectors via malicious users or compromised accounts, arbitrary JavaScript cannot be stored in options or meta and then output as-is.

CSS should also generally be avoided, but if absolutely necessary, it’s a good idea to properly sanitize it. See art-direction-redux, for an example.

Uncached Functions

WP provides a variety of functions that interact with the database, not all of which are cacheble. To ensure high performance and stability, please avoid using any of the functions listed on our Uncached Functions list.

Whitelisting values for input/output validation

When working with user-submitted data, try where possible to accept data only from a finite list of known and trusted values. For example:

$possible_values = array( 'a', 1, 'good' );
if ( ! in_array( $untrusted, $possible_values, true ) )
die( "Don't do that!" );

Encoding values used when creating a url or passed to add_query_arg()

Add_query_arg() is a really useful function, but it might not work as intended.
The values passed to it are not encoded meaning that passing

$m_yurl = 'admin.php?action=delete&post_id=321';
$my_url = add_query_arg( 'my_arg', 'somevalue&post_id=123', $my_url );

You would expect the url to be: admin.php?action=delete&post_id=321&somevalue%26post_id%3D123
But in fact it becomes: admin.php?action=delete&post_id=321&somevalue&post_id=123

Using rawurlencode() on the values passed to it prevents this.
https://vip.wordpress.com/documentation/encode-values-passed-to-add_query_arg/

Using rawurlencode on any variable used as part a the query string, either by using add_query_arg() or directly by string concatenation will also prevent parameter hijacking.

Prefixing functions, constants, classes, and slugs

Per the well-known WordPress adage: prefix all the things.

This applies to things obvious things such as names of function, constants, and classes, and also less obvious ones like post_type and taxonomy slugs, cron event names, etc.

Using Theme Constants

On WordPress.com, there are a few circumstances where services and plugins will load your theme’s functions.php even if your theme isn’t directly accessed (such as our Post-by-email service, our jobs servers, the wp-api etc)

This means constants such as TEMPLATEPATH and STYLESHEETPATH will not be defined or available, and using them in your theme will likely result in fatal errors.

So:

Instead of TEMPLATEPATH, use get_template_directory()
Instead of STYLESHEETPATH, use get_stylesheet_directory()

session_start() and other session-related functions

Creating a session writes a file to the server and is unreliable in a multi-server environment.

Not checking return values

When defining a variable through a function call, you should always check the function’s return value before calling additional functions or methods using that variable.

function wpcom_vip_meta_desc() {
   $text = wpcom_vip_get_meta_desc();
      if ( !empty( $text ) && ! is_wp_error( $text ) {
         echo "n<meta name="description" content="$text" />n";
      }
}

Order By Rand

MySQL queries that use ORDER BY RAND() can be pretty challenging and slow on large datasets. You can either retrieve 100 posts and pick one at random or use this helper function: https://vip.wordpress.com/functions/vip_get_random_posts/

Manipulating the timezone server-side

Using date_default_timezone_set() and similar isn’t allowed because it conflicts with stats and other systems. Developers instead should use WordPress’s internal timezone support. More information.

Removing the admin bar

The WordPress.com admin bar cannot be removed as it’s integral to the user experience on WordPress.com.

Working with wp_users and user_meta

As a large multisite install, WordPress.com has a global users database.

Note that this means that you cannot create, edit, or delete users. For greater level of control, use Guest Authors.

This table is huge on WordPress.com and queries on it can easily cause performance issues. This includes doing any JOIN or meta operations against this set of tables. For parsing through a list of users, use get_users() and iterate in PHP.

For storing user additional user metadata, you should look at User Attributes.

Caching large values in options

This cache object (and any object in wp_cache in general) must not exceed 1MB. On WordPress.com, options are cached in memory to avoid database lookups, which speed things up. This is only effective if the cached object is kept small. Once the object reaches 1MB, it will no longer cache and requests are sent to the database servers, which, depending on the traffic of the site, can cause a flood of requests and have a severe impact on performance. More information. This 1MB limit is the total limit of all options in the options table. This behaviour is different from the core WordPress implementation, having autoload set to false will not impact this 1MB limitation. One option for getting around this problem is to use the wp_large_options plugin for large option values.

Skipping Batcache

Requests that prevent Batcache from caching the page like using $_GET params (e.g. ?abc=def) are not allowed, as they will likely make your site go down. You can use one of the whitelisted params that do not bypass batcache from this list: ‘hpt’, ‘eref’, ‘iref’, ‘fbid’, ‘om_rid’, ‘utm’, ‘utm_source’, ‘utm_content’, ‘utm_medium’, ‘utm_campaign’, ‘utm_term’, ‘utm_affiliate’, ‘utm_subid’, ‘utm_keyword’, ‘fb_xd_bust’, ‘fb_xd_fragment’, ‘npt’, ‘module’, ‘iid’, ‘cid’, ‘icid’, ‘ncid’, ‘snapid’, ‘_’, ‘fb_ref’, ‘fb_source’, ‘_ga’,’hootPostID’ if you want to handle the query data in Javascript. More information.

You should try and implement your URLs using rewrite rules. If you’re having trouble, get in touch and we’ll help 🙂

Ajax calls on every pageload

Making calls to admin-ajax.php on every pageload, or on any pageload without user input, will cause performance issues and need to be rethought. If you have questions, we would be happy to help work through an alternate implementation.

Front-end db writes

Functions used on the front-end that write to the database are not allowed. This is due to scaling concerns and can easily bring down a site.

*_meta as a hit counters

Please don’t use meta (post_meta, comment_meta, etc.) to track counts of things (e.g. votes, pageviews, etc.). First of all, it won’t work properly because of caching and due to race conditions on high volume sites. It’s also just a recipe for disaster and easy way to break your site. In general you should not try to count/track user events within WordPress; consider using a Javascript-based solution paired with a dedicated analytics service (such as Google Analytics) instead.

eval() and create_function()

Both these functions can execute arbitrary code that’s constructed at run time, which can be created through difficult-to-follow execution flows. These methods can make your site fragile because unforeseen conditions can cause syntax errors in the executed code, which becomes dynamic. A much better alternative is an Anonymous Function, which is hardcoded into the file and can never change during execution.

If there are no other options than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

We strongly recommend using Anonymous Functions, which are much cleaner and more secure.

switch_to_blog()

Not something you should ever need to do in a VIP theme context. Use an API (XML-RPC, REST) to interact with other sites if needed.

get_site_*()

Not something you should ever need to do in a VIP context. Because WordPress.com is a multisite these are shared between all our sites. this means you cannot use functions like get_site_transient(), set_site_transient() or get_site_option() set_site_option()

No LIMIT queries

Using posts_per_page (or numberposts) with the value set to -1 or an unreasonably high number or setting nopaging to true opens up the potential for scaling issues if the query ends up querying thousands of posts.

You should always fetch the lowest number possible that still gives you the number of results you find acceptable. Imagine that your site grows over time to include 10,000 posts. If you specify -1 for posts_per_page, you’ll query with no limit and fetch all 10,000 posts every time the query runs, which is going to destroy your site’s performance. If you know you’ll never have more than 15 posts, then set posts_per_page to 15. If you think you might have more than 15 that you’d want to display but doubt it’d hit more than 100 ever, set the limit to 100. If it gets much higher than that, you might need to rethink the page architecture a bit.

A bit on Cron-jobs

Please keep in mind that overly frequent cron events (anything less than 15 minutes) can significantly impact the performance of the site, as can cron events that are expensive. This is because cron-jobs run on the same webservers as the site, and use the same database-servers.

Also, for any cron-jobs that perform sensitive functions (e.g., send emails, alter data in the database), or for jobs that run for more than a minute, we recommend two key actions to be performed. They, in combination, will help getting your cron-job to run smoothly.

First, let us know that you want the cron-job to be executed on our jobs-system. This will not require any change to your code, and only impacts how the cron-jobs are launched. Second, implement locking. The aim of the lock is to make sure no other process is executing the same cron-job simultaneously. The lock is needed, because the WordPress cron-system will schedule a job, even if a previous one is still running, and so two or more can be running at once.

Below there is an example locking-code that you can use, but keep in mind that it will require alterations to fit your theme and the interval your cron-job runs at.

function some_cron_job( ) {
    // Throttle so to guarantee only one process executing this code at once  
    if ( false === get_transient( 'some_cron_job_lock' ) ) {
        // set for 50 minutes
        set_transient( 'some_cron_job_lock', 1, ( 50 * 60 ) );  
    } else { 
        // stop running if locked  
        return;  
    }

    // Code that should get executed below   
    // .....
}

Flash (.swf) files

Flash (.swf) files are not permitted on WordPress.com as they often present a security threat (largely due to poor development practices or due to bugs in the Flash Player) and vulnerabilities are hard to find/detect/secure. Plus, who needs Flash? 🙂

Correct licenses

All plugin and theme code on WordPress.com must be compatible with the GNU Public License v2 (GPL2) license, the same license used for WordPress. Custom code written in-house is fine as long as it complies with the license.

The reasoning for this is that the GPL is the foundation of the WordPress open source project; we want to respect all of the developers who choose to honor this license, and who contribute to the community by building fully GPL compatible themes/plugins.

Ignore development only files

If it’s feasible within your development workflow, we ask that you .svnignore any files that are use exclusively in local development of your theme, these include but are not limited to .git, .gitignore, config.rb, sass-cache, grunt files, PHPUnit tests, etc.

Plugin Registration Hooks

register_activation_hook() and register_deactivation_hook() are not supported because of the way plugins are loaded on WordPress VIP using wpcom_vip_load_plugin(). Read more here

VIP Requirements

Every theme must include a VIP attribution link and wp_head() and wp_footer() calls.

Unprefixed Functions, Classes, Constants, Slugs

Long-standing WordPress best practice. Always namespace things in code to avoid potential conflicts. See Prefix Everything.

Commented out code, Debug code or output

VIP themes should not contain debug code and should not output debugging information. That includes the use of functions that provide backtrace information, such as “wp_debug_backtrace_summary()” or “debug_backtrace()”. If you’re encountering an issue that can’t be debugged in your development environment, we’ll be glad to help troubleshoot it with you. The use of commented out code should be avoided. Having code that is not ready for production on production is bad practice and could easily lead to mistakes while reviewing (since the commented out code might not have been reviewed and the removing on a comment might slip in accidently).

Generating email

To prevent issues with spam, abuse or other unwanted communications, your code should not generate, or allow users to generate, email messages to site users or user-supplied email addresses beyond the core “subscribe” features offered on WordPress.com. That includes mailing list functionality, invitations to view or share content, notifications of site activity, or other messages generated in bulk. Where needed, you can integrate third-party services that allow sharing of content by email, as long as they don’t depend on WordPress.com infrastructure for message delivery.

Custom wp_mail headers

The PHP Mailer is properly escaping headers for you only in case you’re using appropriate filters inside WordPress. Every time you want to create custom headers using user supplied data (eg.: “FROM” header), make sure you’re using filters provided by WordPress for you. See https://developer.wordpress.org/reference/hooks/wp_mail_from/ and https://developer.wordpress.org/reference/hooks/wp_mail_from_name/

Serializing data

Unserialize has known vulnerability problems with Object Injection. JSON is generally a better approach for serializing data.

Including files with untrusted paths or filenames

locate_template(), get_template_part() and sometimes include() or require() are typically used to include templates. If your template name, file name or path contains any non-static data or can be filtered, you must validate it against directory traversal using validate_file() or by detecting the string “..”

Settings alteration

Using ini_set() for alternating PHP settings, as well as other functions with ability to change configuration at runtime of your scripts, such as error_reporting(), is prohibited on the WordPress.com VIP platform. Allowed error reporting in production can lead to Full Path Disclosure.

pre_option_*

Since the theme is being loaded even in non-standard situations (api, jobs system) you should always check if current blog_id matches the real blog_id of the site running the theme.

Here’s how to do it:

$real_current_blog_id = get_current_blog_id();
//foreach( ... )
add_filter( "pre_option_{$option_name}", function( $value ) use ( $real_current_blog_id, $real_value ) {
    if ( get_current_blog_id() === $real_current_blog_id ) {
        return $real_value;
    } else {
        return $value;
    }
});
...

The pre_option_ hooks you should be extra careful with are:

  • pre_option_blogname
  • pre_option_blogurl
  • pre_option_post_count

Minified Javascript files

Javascript files that are minified should also be committed with changes to their unminified counterparts.  Minified files cannot be read for review, and are much harder to work with when debugging issues.

Inserting HTML directly into DOM with Javascript

To avoid XSS, inserting HTML directly into the document should be avoided.  Instead, DOM nodes should be programmatically created and appended to the DOM.  This means avoiding .html(), .innerHTML(), and other related functions, and instead using .append(), .prepend(),.before(), .after(), and so on.  More information.

reCaptcha for Share by Email

To protect against abuse of Jetpack’s share by e-mail feature (aka Sharedaddy) it must be implemented along with reCaptcha. This helps protect against the risk of the WordPress.com network being seen as a source of e-mail spam, which would adversely affect VIP sites. This blog post explains how to implement reCaptcha.

Querying on meta_value

WordPress’ postmeta and termmeta tables have an index on meta_key but no index on meta_value. Using WP_Query to perform a meta_value lookup will likely not scale and should be avoided. See Querying on meta_value for more detailed information on how to achieve the desired results.

flush_rewrite_rules

Your theme’s rewrite rules are flushed automatically on every deploy (and when you switch themes).
There is no need to ever call flush_rewrite_rules() on WordPress VIP. For more information read our documentation on rewrite rules

Implicit File Includes

All files should be included explicitly. For example don’t use glob() or another such function to include all the PHP files in a folder. Patterns such as this:

foreach ( glob( __DIR__ . 'sub_dir/*.php' ) as $file ) {
        require_once( $file );
}

Make it harder to debug as it’s not explicit when each file is loaded. It also can cause problem with load ordering and might cause unexpected behaviours in the future as some files may be unexpectedly loaded.

Error Control Operators

The at sign (@) used for ignoring any error messages that might be generated by an expression are often hiding bugs and make the debugging hard. Any expression which might generate errors or warnings should be sanitised properly by performing related checks. For instance:

@include( __dir__ . '/file-which-does-not-exist.php' ); //__doing_it_wrong();

if ( true === file_exists( __dir__ . ‘/file-which-does-not-exist.php’ ) ) {
include( __dir__ . ‘/file-which-does-not-exist.php’ );
}


Proceed with Caution

The following approaches should be considered carefully when including them in your VIP theme or plugin.

Remote calls

Remote calls such as fetching information from external APIs or resources should rely on the WordPress HTTP API (no cURL) and should be cached. Example of remote calls that should be cached are wp_remote_get(), wp_safe_remote_get() and wp_oembed_get(). More information.

Using __FILE__ for page registration

When adding menus or registering your plugins, make sure that you use an unique handle or slug other than __FILE__ to ensure that you are not revealing system paths.

Functions that use JOINS, taxonomy relation queries, -cat, -tax queries, subselects or API calls

Close evaluation of the queries is recommended as these can be expensive and lead to performance issues. Queries with known problems when working with large datasets:

  • category__and, tag__and, tax_query with AND
  • category__not_in, tag__not_in, and tax_query with NOT IN (these should never be used unless using Elasticsearch)
  • tax_query with multiple taxonomies

For Taxonomy not in queries the code can be refactored to query more than the wanted amount of posts and then skip the posts in PHP if they have the category assigned to them. You can also often refactor these categories into separate post_types so creating a post_type called breaking_news instead of a category and when appropriate joining both post_types. Elasticsearch can handle these types of query very well and if you have Elasticsearch on your account you can offload it by passing ‘es’ => true to the query.

Taxonomy queries that do not specify ‘include_children’ => false

include_children would previously default to false on WordPress.com but as of 4.4 defaults to true. This means that a previously simple one term query could become a very big query. These queries will often timeout on large datasets. For more information see https://vip.wordpress.com/documentation/term-queries-should-consider-include_children-false/

Custom roles

For best compatibility between environments and for added security, custom user roles and capabilities need to be managed via our helper functions.

Caching constraints

As we’re running batcache, server side based client related logic will not work. This includes things like logic based on $_SERVER[‘REMOTE_ADDR’] or similar. This should be switched to a js based approach or a cookie needs to be set and a batcache exception based on the cookie needs to be made.

Because Batcache caches fully rendered pages, per-user interactions on the server-side can be problematic. This means usage of objects/functions like $_COOKIE, setcookie,$_SERVER['HTTP_USER_AGENT'], and anything that’s unique to an individual user cannot be relied on as the values may be cached and cross-pollution can occur.

In most cases, any user-level interactions should be moved to client-side using javascript. More information.

Using extract()

extract() should never be used because it is too opaque and difficult to understand how it will behave under a variety of inputs. It makes it too easy to unknowingly introduce new variables into a function’s scope, potentially leading to unintended and difficult to debug conflicts.

Inline resources

Inlining images, scripts or styles has been a common work around for performance problems related to HTTP 1.x As more and more of the web is now served via newer protocols (SPDY, HTTP 2.0) these techniques are now detrimental as they cannot be cached and require to be sent every time with the parent resource. Read more about this here

Using output buffering

Output buffering should be used only when truly necessary and should never be used in a context where it is called conditionally or across multiple functions / classes. This sort of behaviour can easily interact with batcache and lead to problems with full page caching. It is also hard to debug and to follow what is happening. If used it should always be in the same scope and not with conditionals.

Using $_REQUEST

$_REQUEST should never be used because it is hard to track where the data is coming from (was it POST, or GET, or a cookie?), which makes reviewing the code more difficult. Additionally, it makes it easy to introduce sneaky and hard to find bugs, as any of the aforementioned locations can supply the data, which is hard to predict.Much better to be explicit and use either $_POST or $_GET instead.

Using == instead of ===

PHP handles type juggling. Meaning that this:

$var = 0;
if ( $var == 'safe_string' ){
    return true;
}

Will return true. Unless this is the behavior you want you should always use === over ==.
Other interesting things that are equal are:

  • (bool) true == ‘string’
  • null == 0
  • 0 == ‘0SQLinjection’
  • 1 == ‘1XSS’
  • 0123 == 83 (here 0123 is parsed as an octal representation)
  • 0xF == 15 (here 0xF is parsed as an hexadecimal representation of a number)
  • 01 == ‘1string’
  • 0 == ‘test’
  • 0 == ”

Using in_array() without strict parameter

PHP handles type juggling. This also applies to in_array() meaning that this:

in_array( 0, ['safe_value', 'another string']);

Will return true. Unless this is the behavior you want you should always set the strict parameter to true. See Using == instead of ===

Check for is_array(), !empty() or is_wp_error()

Before using a function that depends on an array, always check to make sure the arguments you are passing are arrays. If not PHP will throw a warning.

For example instead of

$tags = wp_list_pluck( get_the_terms( get_the_ID(), 'post_tag') , 'name');

do:

$tags_array = get_the_terms( get_the_ID(), 'post_tag');
//get_the_terms function returns array of term objects on success, false if there are no terms or the post does not exist, WP_Error on failure. Thus is_array is what we have to check against
if ( is_array( $tags_array ) ) {
    $tags = wp_list_pluck( $tags_array , 'name');
}

Here are some common functions / language constructs that are used without checking the parameters before hand:
foreach() array_merge(), array_filter(), array_map(), array_unique(), wp_list_pluck()
Always check the values passed as parameters or cast the value as an array before using them.

Not Using the Settings API

Instead of handling the output of settings pages and storage yourself, use the WordPress Settings API as it handles a lot of the heavy lifting for you including added security.

Make sure to also validate and sanitize submitted values from users using the sanitize callback in the register_setting call.

Using Page Templates instead of Rewrites

A common “hack” in the WordPress community when requiring a custom feature to live at a vanity URL (e.g. /lifestream/) is to use a Page + Page Template. This isn’t ideal for numerous reasons:

  • Requires WordPress to do multiple queries to handle the lookup for the Page and any additional loops your manually run through.
  • Impedes development workflow as it requires the Page to be manually created in each environment and new developer machines as well.

Not defining post_status Or post_type

By default the post_status of a query is set to publish for anonymous users on the front end. It is not set in any WP_ADMIN context including Ajax queries. Queries on the front end for logged in users will also contain an OR statement for private posts created by the logged in user, even if that user is not part of the site. This will reduce the effectiveness of MySQL indexes, specifically the type_status_date index.
The same is true for post_type, if you know that only a certain post_type will match the rest of the query (for example for a taxonomy, meta or just general query) adding the post_type as well as the post_status will help MySQL better utilize the indexes as it’s disposal.

Use wp_json_encode() over json_encode()

wp_json_encode() will take care of making sure the string is valid utf-8 while the regular function will return false if it encounters invalid utf-8. It also supports backwards compatibility for versions of PHP that do not accept all the parameters.

Using closing PHP tags

All PHP files should omit the closing PHP tag to prevent accidental output of whitespace and other characters, which can cause issues such as ‘Headers already sent‘ errors. This is part of the WordPress Coding Standards.

Use wp_safe_redirect() instead of wp_redirect()

Using wp_safe_redirect(), along with the allowed_redirect_hosts filter, can help avoid any chances of malicious redirects within code.  It’s also important to remember to call exit() after a redirect so that no other unwanted code is executed.

Mobile Detection

When targeting mobile visitors, jetpack_is_mobile() should be used instead of wp_is_mobile.  It is more robust and works better with full page caching.

Using bloginfo() without escaping

Keeping with the theme of Escaping All the Things, code that uses bloginfo() should use get_bloginfo() instead so that the data can be properly late escaped on output.  Since get_bloginfo() can return multiple types of data, and it can be used in multiple places, it may need escaped with many different functions depending on the context:

echo '<a href="' . esc_url( get_bloginfo( 'url' ) ) . '">' . esc_html( get_bloginfo( 'name' ) ) . '</a>';

echo '<meta property="og:description" content="' . esc_attr( get_bloginfo( 'description' ) ) . '">';

Performance Considerations

We want to make sure that your site runs smoothly and can handle any traffic load. As such, we check your site for performance considerations such as: are remote requests fast and cached? Does the site request more data than needed?

Uncached Pageload

Uncached pageloads should be optimized as much as possible. We will load different pages and templates on your theme uncached, looking for slow queries, slow or timed out remote requests, queries that are overly repeated, or function routines that are slow.

Memcache hits/misses

Memcache misses or over-additions/updates can be a sign of potential problems.

    • Clear your cache on a page
    • In the “Memcache” tab in the Debug Bar, check the ratio of sets/adds vs gets. You should see almost as many sets/adds as gets.
    • Reload the page (without clearing the cache)
    • In the “Memcache” tab in the Debug Bar, check the ratio of sets/adds vs gets. You should see (almost) no sets/adds.
    • Reload the page a few more times and check the set/add-to-get ratio; the former should continue to remain 0 or minimal.

If you’re still seeing sets/adds in subsequent pages, that means that something is constantly being added to the cache that shouldn’t.

A/B Testing

A/B tests can help you make informed decisions about how to structure your site — with an A/B test, you don’t have to guess which version your readers will prefer. You can run an experiment to test, gather data, and measure the results.

On WordPress.com VIP, you can use any client-side A/B testing framework like Optimizely for basic tests or the CheezTest plugin to create and run Batcache-compatible server-side A/B tests in your theme.

If you have any questions about using these tools, please contact the VIP team.

Custom Error Pages

We have error pages that are standard and served for all sites on WordPress.com, and as a VIP customer you can override these defaults and specify your own custom error pages instead.

Setting it up is simple: all you need to do is add a custom error page (a simple HTML file) to your theme.

The file needs to be located in a folder called “error-docs” and named “error-page.html”. Note that the file can only contain HTML and basic inline or remote-hosted CSS and Javascript.

I.e., from the root of your theme: ~/error-docs/error-page.html

Once you’ve committed the file to your theme, you’ll need to open a ticket with our team to notify us, so we can make some associated configuration changes on our end.

Using Ajax with Credentials when Using Separate Domains for Admin and Front-end or when Uploading Files

Handling file uploads from the frontend of a site requires a few extra considerations to ensure everything works smoothly.

Handling Ajax Requests

On WordPress.com VIP, the frontend and backend of your site exist on two different domains. When submitting frontend forms via ajax, you’ll need to take care to send credentials to work around cross domain limitations. For example, a jQuery ajax request would need withCredentials: true added to the request:

jQuery.ajax({
   url: myBackendUrl,
   xhrFields: {
      withCredentials: true
   }
});

This applies equally when using an ajax form plugin, such as jQuery.form:

jQuery( '#myform' ).ajaxSubmit({
    // ... ajax options
    xhrFields: {
        withCredentials: true
    }
});

Choosing an Endpoint

When handling file uploads from the frontend, be sure to use the wp-admin/admin-post.php endpoint, instead of wp-admin/admin-ajax.php, as the former has a much higher upload size limit than the latter, which is only about 50mb. Only wp-admin/admin-post.php should be used for receiving files via ajax.

WP Frontend Uploader Plugin

WordPress.com VIP provides a ready made plugin for handling frontend uploads from visitors – WP Frontend Uploader. Using this plugin is recommended for those who want to quickly add frontend upload capabilities to their site.

List Posts By A Co-Author

When using Co-Authors Plus, you may want to create a listing of all posts by a given co-author. Co-Authors Plus deviates slightly from how core WordPress works in that it stores byline information in a custom ‘author’ taxonomy. It works in this manner because a post (let it be a Post, Page, or Custom Post Type) can have multiple taxonomy terms associated with it.

To list some or all posts from a co-author, you’ll want to create a new WP_Query object based on the author term for a given user or guest author. Here’s an example of what that might look like:

// Build the query arguments
$args = array(
	'post_type' => 'post',
	'posts_per_page' => 10,
	'post_status' => 'publish',
	'author_name' => $user_login,
);
$author_query = new WP_Query( $args );

if ( $author_query->have_posts() ) :
	while ( $author_query->have_posts() ) : $author_query->the_post();

	// Do your presentation

	endwhile;
endif;

Customizing Publicize Sharing Behavior

Publicize makes it easy to automatically share WordPress.com posts on Facebook, Twitter, Tumblr, LinkedIn, and Yahoo!

WordPress.com VIP clients can customize which shortlink Publicize uses, when Publicize shares to which accounts, and other behavior changes using standard filters.

Conditionally allow services or connections to be utilized

Publicize includes an extremely helpful wpas_submit_post? filter for determining whether a given post should be submitted to a given service or connection. It looks like this:

$submit_post = apply_filters( 'wpas_submit_post?', true, $post_id, $service_name, $connection_data ) )

$service_name will be a value like ‘twitter’ or ‘facebook’, and $connection_data will have metadata about the connection.

Here’s how you might reserve a “@vipwpnews” Twitter account exclusively for posts in the “WordPress” category:

add_filter( 'wpas_submit_post?', 'vipx_wpas_submit_post', 10, 4 );
function vipx_wpas_submit_post( $ret, $post_id, $name, $connection ) {

	$categories = get_the_terms( $post_id, 'category' );
	if ( 'twitter' == $name && '@vipwpnews' == $connection['meta']['display_name'] ) {

		if ( is_array( $categories ) )
			$categories = wp_list_pluck( $categories, 'slug' );

		if ( empty( $categories ) || ! in_array( 'wordpress', $categories ) )
			$ret = false;

	}
	return $ret;
}

Note: This filter is applied both when the post is published and in the post metabox to determine which services should appear as available to the writer or editor. It will also let authors add their own services.

Add a checkbox to send new post updates to Publicize

When liveblogging or making frequent updates to a post, you may want to send multiple updates to Publicize.

Publicize’s default behavior is to only syndicated a post once. You can add a checkbox for writers or editors to publicize a post a second time using this code snippet:

add_action( 'publicize_form', 'vipx_filter_publicize_form' );
function vipx_filter_publicize_form( $form ) {
	global $post;

	// Only add the checkbox if the post was already published
	if ( 'publish' != $post->post_status )
		return $form;

	$checkbox = '<label for="vipx-republicize"><input type="checkbox" id="vipx-republicize" name="vipx-republicize" /> Re-Publicize Post?</label>';

	$form .= $checkbox;

	return $form;
}

add_action( 'save_post', 'vipx_action_save_post_republicize', 5 );
function vipx_action_save_post_republicize( $post_id ) {

	if ( isset( $_POST['vipx-republicize'] ) ) {
		update_post_meta( $post_id, '_publicize_pending', true );
		add_filter( 'wpas_force_publicize', '__return_true' );
	}
}

The message shared to the service will be whatever is in the Publicize textarea.

Implement your own URL-shortening service

By default the Publicize feature uses wp.me as a URL-shortening service. You can also use any other URL-shortening service that can return a shortened URL.

The easiest way is to filter pre_get_shortlink or get_shortlink (called by wp_get_shortlink). For an example, check out the bit.ly plugin.

The following filter is available to alter the URL sent in your update:

$url = apply_filters( 'wpas_post_url', wp_get_shortlink( $post->ID, true ), $post->ID, $this->slug );

Altering the default messages

It is also possible to change the default message that is created with the following filters:

apply_filters( 'wpas_default_message', $this->default_message, $this->slug )
apply_filters( 'wpas_default_prefix', $this->default_prefix, $this->slug )
apply_filters( 'wpas_default_suffix', $this->default_suffix, $this->slug )

These filters are used in the following context:

$title = sprintf( $this->default_prefix, $url ) . sprintf( $this->default_message, $post->post_title, $url ) . sprintf( $this->default_suffix, $url );

and allow the wildcards '%title%', %url% within the default_message/prefix/suffix variables.

You can also alter the message that is sent to Twitter / Facebook with a simple function attached to the following filter to Twitter:

$status_update = apply_filters( 'publicize_twitter_message', $message, $post, $url );

and to Facebook:

$status_update = apply_filters( 'publicize_facebook_message', $custom, $post, $url );

Configure Ad Code Manager to manage the advertisements on your site

Ad Code Manager is a VIP-sponsored plugin designed to make it easier to manage the ad codes used to display advertisements on your site. There’s a little bit of work you’ll need to do up front, however, in order to integrate Ad Code Manager with your theme.

Note: WordPress.com Enterprise users should contact support and we’ll take care of the configuration for you.

The high-level idea behind Ad Code Manager is that it gives non-developers an admin interface to manage your ad codes. It then permits users to (optionally) target specific ad codes using conditionals like is_home() and is_single(). Ad codes are associated with positions in the theme through the use of ad tags.

Currently, Ad Code Manager easily integrates with Google Doubleclick For Publishers Async and Google AdSense. Other ad providers are supported with additional configuration.

Google AdSense and DoubleClick For Publishers Async

Let’s use AdSense as our first example. You’ll want to incorporate some of the default ad tags into your theme by use of do_action(). Here’s an example you might put in your header.php file:

do_action( 'acm_tag', '728x90_leaderboard' );

Once you’ve done so, you can select the “Google AdSense” provider in the admin. Ad codes can be registered against ad tags (positions) by choosing the ad tag from the drop down, entering the tag ID and publisher ID, and hitting “Add New Ad Code”.

Google AdSense configuration

And like that, your 728×90 leaderboard will appear on your site.

The Google AdSense configuration comes with many of Google’s suggested sizes. Additional ad tags can be registered by the way of filtering:

add_filter( 'acm_ad_tag_ids', 'acmx_filter_ad_tag_ids' );
function acmx_filter_ad_tag_ids( $ids ) {

	$ids[] = array(
		'tag'       => '100x100_smallsquare',
		'url_vars'  => array(
			'tag'       => '100x100_smallsquare',
			'height'    => '100',
			'width'     => '100',
			),
		'enable_ui_mapping' => true,
	);

	return $ids;
}

Keep in mind that you’ll still need to incorporate a do_action( 'acm_tag', '100x100_smallsquare' ); in your theme in order to display the ad tag.

If you choose Google DFP Async as your provider, you’ll likely need to register additional ad tags, as we only package two default ad tags.

Custom Ad Provider Implementations

As mentioned previously, other ad code providers are supported with additional configuration. Here’s an example of the different filters you would use to configure the older version of Google Doubleclick For Publishers:

<?php
/**
 * Define the default URL to be used when rendering ad codes
 */
add_filter( 'acm_default_url', 'acmx_filter_default_url' ) ;
function acmx_filter_default_url( $url ) {
	if ( 0 === strlen( $url )  ) {
		return "http://ad.doubleclick.net/adj/%site_name%/%zone1%;s1=%zone1%;s2=;pid=%permalink%;fold=%fold%;kw=;test=%test%;ltv=ad;pos=%pos%;dcopt=%dcopt%;tile=%tile%;sz=%sz%;";
	}
}

/**
 * Whitelist the DFP URL to be used in ad tags. The whitelist
 * helps prevent execution of arbitrary scripts
 */
add_filter( 'acm_whitelisted_script_urls', 'acmx_filter_whitelisted_script_urls');
function acmx_filter_whitelisted_script_urls( $whitelisted_urls ) {
	$whitelisted_urls = array( 'ad.doubleclick.net' );
	return $whitelisted_urls;
}

/**
 * Define the different ad tags (locations) you'd like to use in your theme
 */
add_filter( 'acm_ad_tag_ids', 'acmx_ad_tags_ids' );
function acmx_ad_tags_ids( $ad_tag_ids ) {
	return array(
			array(
					'tag' => '728x90-atf',
					'url_vars' => array(
						'sz' => '728x90',
						'fold' => 'atf',
						'width' => '728',
						'height' => '90',
				)
			),
			array(
					'tag' => '728x90-btf',
					'url_vars' => array(
						'sz' => '728x90',
						'fold' => 'btf',
						'width' => '728',
						'height' => '90',
				)
			) ,
			array(
					'tag' => '300x250-atf',
					'url_vars' => array(
						'sz' => '300x250',
						'fold' => 'atf',
						'width' => '300',
						'height' => '250',
				)
			),
			array(
					'tag' => '300x250-btf',
					'url_vars' => array(
						'sz' => '300x250',
						'fold' => 'btf',
						'width' => '300',
						'height' => '250',
				)
			),
			array(
					'tag' => '160x600-atf',
					'url_vars' => array(
						'sz' => '160x600',
						'fold' => 'atf',
						'width' => '160',
						'height' => '600',
				)
			),
			array(
					'tag' => '1x1',
					'url_vars' => array(
						'sz' => '1x1',
						'fold' => 'int',
						'pos' => 'top',
					)
			)
		);	
}

/**
 * Register the full <script> output to use with each ad tag
 */
add_filter( 'acm_output_html','acmx_filter_output_html', 5, 2 );
function acmx_filter_output_html( $output_html, $tag_id ) {
	$output_html = '<!-- DFP %pos% %sz% ad tag --> 
	<script language="JavaScript" type="text/javascript">
if (typeof ord=='undefined') {ord=Math.random()*10000000000000000;}
if (typeof(dfp_tile) == 'undefined') dfp_tile=%tile%;
document.write('<script language="JavaScript" src="%url%ord=' + ord + '?" type="text/javascript"></script>');
</script><noscript><a href="%url%ord=%random%?" target="_blank"><img src="%url%ord=%random%?" width="%width%" height="%height%" border="0" alt=""></a></noscript>
<!-- //DFP %pos% %sz% tag -->';
	return $output_html;
}

/**
 * Fine tune our output tokens
 * This is the real example of how easily you can modify output
 * depending on your ad network specs
 */
add_filter('acm_output_tokens', 'acmx_filter_output_tokens', 5, 3 );
function acmx_filter_output_tokens( $output_tokens, $tag_id, $code_to_display ) {
	global $dfp_tile;
	global $dfp_ord;
	global $dfp_pos;
	global $dfp_dcopt;
	global $wp_query;
	
	// We can't really rely on get_permalink() so use $_SERVER['REQUEST_URI] as bulletproof solution for generating unique pids
	$link = strlen( $_SERVER['REQUEST_URI'] ) > 1 ? sanitize_key( $_SERVER['REQUEST_URI'] ) : home_url();
	$output_tokens['%permalink%'] = str_replace( array( '/',':', '.' ), "", $link ); 
	$output_tokens['%random%'] = $dfp_ord;
	$output_tokens['%tile%'] = ++$dfp_tile;
	if (  false === $dfp_pos[ $code_to_display['url_vars']['sz'] ] ) {
		$output_tokens['%pos%'] = 'top';
		$dfp_pos[ $code_to_display['url_vars']['sz'] ] = true;
	} else {
		$output_tokens['%pos%'] = 'bottom';
	}
	if ( ! $dfp_dcopt ) {
		$output_tokens['%dcopt%'] = 'ist';
		$dfp_dcopt = true;
	} else {
		$output_tokens['%dcopt%'] = '';
	}
	
	$output_tokens['%test%'] = isset( $_GET['test'] ) && $_GET['test'] == 'on' ? 'on' : '';
	
	return $output_tokens;
}

Register Additional HTML Attributes for TinyMCE and WP KSES

Out of the box, WordPress gives content creators a fair amount of flexibility in what can be entered into the Visual and Text editors. They can enter all sorts of HTML tags which can be a blessing or a curse. You may find you want to register additional HTML elements or attributes for them to use, or to remove ones you don’t want them to use.

To keep additional HTML attributes from being stripped by WP Kses when the post is saved, you’ll need to register them on the $allowedposttags global. Here’s what it would look like:

add_action( 'init', 'vipx_allow_contenteditable_on_divs' );
function vipx_allow_contenteditable_on_divs() {
	global $allowedposttags;

	$tags = array( 'div' );
	$new_attributes = array( 'contenteditable' => array() );

	foreach ( $tags as $tag ) {
		if ( isset( $allowedposttags[ $tag ] ) && is_array( $allowedposttags[ $tag ] ) )
			$allowedposttags[ $tag ] = array_merge( $allowedposttags[ $tag ], $new_attributes );
	}
}

With just that snippet, however, you’ll find that you can save the proper markup in the Text editor but it gets stripped out in the Visual (TinyMCE) editor. To get around this, you’ll need to also register your new attributes with TinyMCE:

add_filter('tiny_mce_before_init', 'vipx_filter_tiny_mce_before_init');
function vipx_filter_tiny_mce_before_init( $options ) {

	if ( ! isset( $options['extended_valid_elements'] ) ) {
		$options['extended_valid_elements'] = '';
	} else {
		$options['extended_valid_elements'] .= ',';
	}

	if ( ! isset( $options['custom_elements'] ) ) {
		$options['custom_elements'] = '';
	} else {
		$options['custom_elements'] .= ',';
	}

	$options['extended_valid_elements'] .= 'div[contenteditable|class|id|style]';
	$options['custom_elements']         .= 'div[contenteditable|class|id|style]';
	return $options;
}

Embedding rich media in your post

As a member of WordPress.com VIP, you are able to embed rich media into your posts. This document will quickly explain how embedding works.

Commonly Used Embeds

Looking to embed content from YouTube, Hulu, InstagramVimeoBlip.tvCNNMoney videoDaily MotionGist or Reddit? Simply copy the URL in your browser bar while viewing the video or photograph, and paste it into your editor on its own line. We’ll automatically embed the content for you.

Note: Make sure the URL is not linked or formatted in any way, and that it is on its own line. You can read more about WordPress’s custom embeds here.

Looking to embed content from Scribd, Slideshare, Wufoo, Flickr Video, SoundCloud or Bandcamp? Each of these services offers a WordPress.com shortcode that you can paste directly into your post editor. Click on the service’s name above for more information on how to embed their content.

Scripts, iFrames, and Objects

WordPress.com VIP handles embeds and scripts that haven’t already been whitelisted above in a special way for security protection. Here’s how to embed code that begins with `<script>, <iframe>, <object>`.

1) In your post editor, there is a tool above the formatting bar that allows you to include scripts. You can click either “Add Media” or “Add Embed.”

Screen Shot 2013-07-22 at 5.55.27 PM

2) A window will pop up. Be sure to select the “Insert Embed” tab. Paste the script code into this window, and click “Insert.”

Screen Shot 2013-07-22 at 5.55.56 PM

3) A shortcode will be inserted in your post, representing your protected embed.

Custom Widths/Heights For “Protected Embeds”

Our “protected embeds” feature attempts to make an educated guess at the ideal width or height of your embed, but if the object you’re embedding doesn’t make those values obvious, we’re not always able to do that. Instead, you can specify your own width or height attributes for the iframes in the shortcode, as such:

protected-iframe id="#" info="#" width="100%" height="200"

Importing Content with Embeds

If you’re importing content from a non-VIP site, you may have embedded scripts, iframes and objects that need to work on your WordPress.com VIP site. To ensure this happens, please open a support ticket and request that we handle the initial import for you, which will allow that embedded content to pass through the import process. Then, when you next edit one of those posts or pages, the embed will be automatically converted to a protected embed.

Ready to get started?

Tell us about your needs

Let us lead the way. We’ll help you select a top tier development partner. We’ll train your developers, operations, infrastructure, and editorial teams. We’ll coarchitect your deployment processes. We will provide live support for peak events. We’ll help your people avoid dark alleys and blind corners, and reduce wasted cycles.