Categories
WordPress

Disable RSS Feed Pages in WordPress

To disable RSS feed pages in WordPress, hook into the action filters provided for each feed page function and then redirect to the home page.

// Disable RSS feed pages
add_action( 'do_feed', 'disable_rss_feed_pages', 1);
add_action( 'do_feed_rdf', 'disable_rss_feed_pages', 1);
add_action( 'do_feed_rss', 'disable_rss_feed_pages', 1);
add_action( 'do_feed_rss2', 'disable_rss_feed_pages', 1);
add_action( 'do_feed_atom', 'disable_rss_feed_pages', 1);
add_action( 'do_feed_rss2_comments', 'disable_rss_feed_pages', 1);
add_action( 'do_feed_atom_comments', 'disable_rss_feed_pages', 1);

function disable_rss_feed_pages() {
    wp_redirect( site_url() );
    exit();
}
Categories
WordPress

WordPress adding slashes in POST requests

WordPress adds slashes before quotes even if we do not want to use magic quotes.

To solve this problem, you can use either of the following two functions on the values returned from POST requests-

  • wp_unslash
  • stripslashes_deep

References:

Categories
WordPress

How to Modify Title Tag in WordPress

I always missed a function to directly change the title tag in WordPress template. But here is a function which can do that for you.

function modify_title( $new_title ) {
    add_action( 'pre_get_document_title', function( $current_title ) use( $new_title ) {
        return $new_title;
    }, 9999 );
}

Please note that this function uses use keyword to bind variables into anonymous function’s scope. Learn more

Categories
WordPress

WP_Query by URL for Infinite Scroll in WordPress

I was trying to create an infinite scroll in WordPress. All I wanted was to parse the next page url without making any changes to the code so that the code becomes interoperable with the pagination templates.

To achieve that, instead of passing custom query parameters to the API, I decided to parse the next page url to run WP_Query without mentioning any additional parameters.

Steps were:

  1. Get the next page url
  2. Parse it to get query parameters of next page
  3. Run WP_Query on that and get the posts of next page

Though I spent hours on this, it turned out to be rather simple.

// Get the url of the next page
$next_page_url = $args[ 'next_page_url' ] ?? $_SERVER['REQUEST_URI'];

// Save the next page url in the current global server variable array
$_SERVER['REQUEST_URI'] = $current_page_url;

// Rebuild the global $_GET variable to include the new query string parameters
parse_str( parse_url( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ?? '', PHP_URL_QUERY ), $_GET );

// Run the wp_query to get the posts of next page
$wp->parse_request();
$wp->query_posts();
$all_posts = $wp_query->posts;

Just replace your pagination links with an element which passes the next page url to the API when it becomes visible. And you can get the posts HTML from the API.

And that’s it. Your infinite scroll is ready.

References:

  1. https://medium.com/@harryhorton/query-wp-rest-api-using-any-permalink-url-f5e4e4dd36b7
Categories
WordPress

Reolved failed upload in WordPress post edit filter

When adding an upload form to the post edit screen in WordPress admin, I found the upload to fail. The $_FILES array was empty.
The reason was that by default, WordPress post edit form does not send files data.

To fix that, we need to add enctype attribute to the form.
Here is the code to do that-

add_action( 'post_edit_form_tag' , 'post_edit_form_tag');
function post_edit_form_tag( ) {
    echo ' enctype="multipart/form-data"';
}
Categories
WordPress

How to customize PHP error message in WordPress

WordPress displays a default error message when it encounters a PHP error-

There has been a critical error on this website.

Learn more about troubleshooting WordPress.

Now this message is subtle, but still reveals 2 things-

  1. Your website has some error
  2. Your website is built on WordPress

Now second point is usually fine unless you specifically do not want WordPress name to appear anywhere on your website.

But the first point can become a security issue. Luckily there is a way to modify it.

This message is handled by WP_Fatal_Error_Handler class in wp-includes folder. Out of many methods, they give option of a drop-in file which can override the default php error message.

Just create a file with the name “php-error.php” and put it in the wp-content folder. Write the html code for PHP error message.

Now whenever WordPress will encounter a php error, it will execute this file and will display whatever you wrote in that file.

Categories
WordPress

How to change custom post permalink in WordPress

I have struggled with this issue for years. I tried different ways but they always felt like hacks and gave inconsistent results most of the time. I also tried a popular plugin which broke my site.

Whenever you add a custom post type in WordPress through code, there is no way to select a permalink structure for it. By default, it’s permalink is of the format- post-type-slug/url-slug.

Though there are plugins to modify the permalink of a custom post type, surprisingly, I could not find solid way to do it through code. But finally, I found it.

In this post, I will show you that how you can modify the permalink of a custom post type with just a few lines of code.

For example, I have a custom post type named "event" and I want to add post id to the end of the permalink.

First, you need to change the rewrite rule for the custom post type. To do this, add following two lines just after the code where you registered your custom post type-

global $wp_rewrite;
$wp_rewrite->extra_permastructs['event']['struct'] = 'contest/%event%-%post_id%';

Now, use the filter hook to change the permalink like so-

add_filter( 'post_type_link', 'modify_permalink', 10, 2 );
function modify_permalink( $post_link, $post ) {
    if ( $post && 'event' === $post->post_type ) {
        return str_replace( '%post_id%', $post->ID, $post_link );
    }
    return $post_link;
}

And that’s it. It was so simple. No need of any bloated plugin which may break your site and add needless overhead.

You can modify the above code to modify permalink based on your requirement.

Reference:

  1. https://wordpress.stackexchange.com/questions/369343/put-post-id-on-the-custom-post-type-url
Categories
WordPress

WordPress: Missing canonical tags on archive pages

WordPress keeps surprising me even after more than a decade since I started using it.

Today I came to know that WordPress only generates canonical tags for singular pages (posts & pages). WordPress does not add canonical tags to archive pages including author page, post type archives, taxonomy archives etc.

So, how to add canonical tags to all archive pages? Use the wp_head action hook. Here is the script-

add_action( 'wp_head', 'add_canonical_url' );
function add_canonical_url() {
    if ( is_archive() ) {
        echo '<link rel="canonical" href="' . get_pagenum_link() . '" />';
    }
}
Categories
WordPress

404 pages getting redirected to home

Today, I wasted major part of my day trying to figure out why my subfolder based WordPress multisite install is redirecting all 404 errors to the site’s home page.

The problem turned out to be the constant “NOBLOGREDIRECT” which I defined in wp-config.php file. This constant ensures that in a multisite install, if anyone tries to access a non-existent site, they will be redirected to the signup page.

Now, this works great in case of subdomain based WordPress multisite setup. But, for subfolder based multisite setup, it actually starts redirecting all 404 pages to the signup page.

I recently converted my WordPress network from subdomain to subfolder structure and that’s why this setting started creating problem after that. If you have a subfolder based multisite install, you do not need NOBLOGREDIRECT.

Hope that helps.

Categories
Coding WordPress

Modify page title tag in WordPress

To change page title tag in WordPress, use the pre_get_document_title filter.

Most of the answers on web have mentioned the filter wp_title, but do not use it as wp_title function will be deprecated in future and wp_title hook will not work.

At present, wp_title filter does not work when modifying the title tag.

Categories
WordPress

Prevent Memory Leak in WordPress

Recently I faced an issue of memory leak in one of my WordPress projects. I was running a function that was reading post meta and user metadata of thousands of objects. I thought reading data from MySQL is cheap in terms of processing power and memory, but it turned out it was causing my function to crash giving an out-of-memory error.

I made sure that there was no update being done to either post meta or user meta. It was only reading data through get_user_meta() and get_post_meta() functions. Then what was the reason for the memory leak?

It turned out that WordPress caches all the results when we read or write to post and user meta. That’s why, on iterating through thousands of posts and users, the result of each was being cached in memory, thus resulting in out-of-memory error.

To fix this issue, we need to prevent WordPress from caching this data. This can be done through wp_suspend_cache_addition(). This function disables the cache addition for the current page execution. This is how we need to call this function at the start of our script.

wp_suspend_cache_addition( true );

And that’s it. Memory usage dropped to less than 6 MB with peak memory usage coming down to mere 13 MB.

If you are facing a similar issue in WordPress, do remember this function. Also, while writing cron scripts or scripts to bulk update data like import/export scripts, it is better to call this function to ensure there is no out-of-memory issue.

Categories
WordPress

Correct Way to Manage Title Tags in WordPress

The title tag is a very important feature of any website. It is displayed at the top of browser tabs and also read by search engines. So, it should be clear to read as well as SEO friendly.

WordPress is so powerful that it has customization options for almost anything in its structure. The title tag is no exception to this. However, while creating a WordPress theme, what is the best way to generate or modify title tags?

The earlier method was to include title tag in WordPress head using wp_title() function. But this method was supposed to be deprecated in WordPress version 4.4, but was kept for backward compatibility.

So, you should not use wp_title() as sooner or later it will be deprecated and removed.

Starting WordPress version 4.1, the recommended way to add title tag is to declare ‘title-tag’ compatibility in the theme itself. You can do this using the following code snippet.

add_theme_support( 'title-tag' );

This code will ensure that title tags are automatically added to the head of all HTML pages (posts, pages, archives, etc.). The format of the title tag is also automatically decided by WordPress. Here is the default structure of the title tags based on the current page-

Home Page- <Site Name><Separator><Site Tagline>

Posts- <Post Title><Separator><Site Name>

Pages- <Page Title><Separator><Site Name>

Archives- <Archive Title><Separator><Site Name>

And similarly all other WordPress generated pages will get automatic title tags.

The values of Site Name and Site Tagline are those which we define in Settings > General.

You can add theme support directly in the theme if you are creating one. Or, you can create a child theme and add this code in its functions.php file.

If you are declaring theme support in a plugin, then use the action hook after_setup_theme to ensure that theme support is added once all the plugins and themes are loaded.

If you are undecided about where to add your code, I have a very good article about where to add custom code in WordPress.

Now, this structure is perfect for most websites and good for SEO. However, in certain scenarios, we may need to modify the title tag.

To do that, WordPress has a filter hook document_title_parts using which we can hook into the title tag generating function and modify it dynamically.

Following is an example snippet of code to do that-

add_filter( 'document_title_parts', 'modify_title_on_home_page' );
function modify_title_on_home_page( $title_array ) {
    $title_array ['title'] = 'Modified Page Title';
}

This code modifies the page title on the home page of a WordPress website.

The document_title_parts filter passes an array containing the title of the current page, page number (in case of paginated pages), site tagline, and site title/name which we can modify and return back.

And that’s it. You are now ready to utilize the power of WordPress to manage the title tags efficiently.

Categories
WordPress

How to change Post Type in WordPress

While working with custom post types in WordPress, many times we come across the need to change the post type of a particular post.

It can be done either directly through code or using a plugin.

Without Plugin

This can be done using WordPress functions- wp_update_post or set_post_type.

wp_update_post can be used when updating multiple fields of a post.

In case, only post type has to be changed, then set_post_type is sufficient.

Just use set_post_type along with the post id and you are done.

If you are unsure about where to add this code, take a look at Where to add custom code in WordPress.

Using Plugin

If you occasionally want to switch posts and do not want to fiddle with the code, there is a good plugin for this which easily performs this task- Post Type Switcher.

Simply install and activate a plugin. It will add the option to change post types in the admin menu.

A good thing about this plugin is that it allows to change the post type of multiple posts in bulk by utilizing the "bulk edit" feature in WordPress.

So, now you know how to change post type with or without a plugin. Which one do you like better? Do let me know in comments section.

Categories
WordPress

How to view and modify WordPress rewrite rules

If you encounter a sudden unexpected delay in page load which was previously working fine, a good place to check is the rewrite rules.

In my case, it seems there was some issue in the currently generated rules which was causing this delay.

A simple visit to Settings->Permalink automatically flushed and regenerated all the rewrite rules and it resolved the issue for me. The page is again loading as fast as it did earlier.

However, if you want to check the current rewrite rules, there is a simple code to check that.

Add the below code to your plugin or theme.

// Filter to display rewrite rules on permalink settings page when debugging 
add_filter( 'rewrite_rules_array', 'show_all_the_rewrite_rules' );
function show_all_the_rewrite_rules( $rules ) {
    echo nl2br( var_export( $rules, true ) );
    die;
}

Now this hook is only called on Permalink Settings page. So, visit that page and you will be able to see all the current rewrite rules of your website.

You can also remove rules if they are not required, based on regex as shown in the following code.

// Filter hook to remove unwanted rewrite rules, will only run when **setting->permalink** page is opened
function remove_rewrite_rules( $rules ) {
    foreach ( $rules as $rule => $rewrite ) {
        if ( preg_match( '/(feed|rss|atom|embed|attachment|trackback|year|date|search/)/', $rule ) ) {
            unset( $rules[$rule] );
        }
    }

    return $rules;
}

You can define any pattern in the preg_match function to remove the unwanted rewrite rules.

Hope this helps.

Categories
WordPress

Whitelist all sub-sites for wp_safe_redirect in WordPress Multisite

In WordPress, there are two functions for redirecting a page- wp_redirect and wp_safe_redirect.

wp_redirect can be used to redirect to any url.

wp_safe_redirect can only redirect to current site. In case any external url is provided, the page is redirected to wp-admin.

For security, it is recommended to use wp_safe_redirect function for any redirects. This works fine for single WordPress installation. But in case of subdomain based WordPress multisite, this fails because each sub-domain is an individual domain for wp_safe_redirect.

What if we want to use wp_safe_redirect to redirect our pages only within network and not outside?

For this purpose, WordPress has a filter to add additional domains to the wp_safe_redirect whitelist. You can add any domain or sub-domain, internal or external, through this method.

In this article, we will focus on how to whitelist all the sub-domains of a network.

Just add the following code to your custom plugin or child theme’s function.php file.

// Filter to add all subdomains to wp_safe_redirect whitelist
add_filter( 'allowed_redirect_hosts', 'whitelist_all_subdomains' );

function whitelist_all_subdomains( $hosts ) {
    $sites = get_sites();
    $domains = array();

    foreach ( $sites as $site ) {
        $domains[] = $site->domain;
    }

    return array_merge( $hosts, $domains );
}

This code gets all the sites through get_sites function and iterates all the sites to create an array of all domains/sub-domains of sub-sites. It then adds that to the whitelist.

If you try now, you will see that page redirects across sub-sites of a network using "wp_safe_redirect" are flawless.

Categories
WordPress

Where to add custom code in WordPress

WordPress offers a lot of features right out of the box. If you want to create a blog, you can start using WordPress without the need to add any additional plugin.

When you want some additional functionality not provided by the core WordPress, you can find and install a plugin from the WordPress plugin repository.

WordPress plugins repository contains thousands of plugins and in most cases, you will find the plugin for your required functionality.

But there are cases when you do not find the perfect plugin. There may be plugins, but they are so bloated that you do not want to use them. Or, you need a very small functionality and installing a full-blown plugin with a lot of unnecessary features may seem illogical.

In such cases, it is always better to write your own code for adding that functionality. But where to add that code?

Where to add the code

If you want to modify a core WordPress feature, you may be tempted to edit the WordPress core files directly. But this is not a sustainable practice as whenever WordPress will be updated, your changes would be overwritten.

If you want to change the functionality of your current theme, you edit the functions.php file inside your theme. But again, if the theme is updated, you will lose the changes.

In short, you must NOT edit any core WordPress files, themes or plugins. Rather, you need to add code to override or extend that functionality based on the APIs provided by WordPress.

There are two recommended ways to add custom code to WordPress-

  • Create a child theme of your current theme and add code to its functions.php file
  • Create a custom plugin and add it to your website

Theme vs Plugin

WordPress has very nicely separated the design and development functionality. Themes are meant for the front-end design of the website and plugins are meant for adding functionality to the website.

It is important to strictly follow this separation logic to ensure a clean and easy to maintain code.

WordPress provides the functionality to add a child theme to override the current theme’s files. You can override templates and add code to functions.php file.

But you must not add any code to a theme that is not related to front-end design. All such code should reside in plugin only. Plugins are the right place for all your non-design functionality.

I have seen a lot of WordPress tutorials on various popular websites that encourage users to add custom code to their child theme’s functions.php file. But this approach is wrong.

If you add your custom code to WordPress child theme, you violate the code separation logic, thus messing up your website for the future.

Creating a small single-page plugin and adding it to WordPress is easier compared to adding a child theme. Plugins are easy to manage and you can easily create a directory structure for your code if you are creating a complex plugin with multiple functions.

Is it safe to add custom code to my WordPress blog

Security is a very important concern when writing code. If you are not a good programmer and somehow you leave any vulnerability in your code, it can be a huge issue for your website. To make sure that this does not happen, you should follow proper coding standards and best practices.

If it is a small function, it is very easy to ensure that it is free from vulnerabilities. But in case you are planning for a complex plugin, make sure that you properly review your code and test the code for all possible scenarios.

If you are a decent programmer, you can write code which is secure and clean. Though security is important, fear of security must not discourage you from creating your own plugin. It actually enhances your skill and gradually you become good at it.

Just carefully write your code, review it properly and test it thoroughly. You can refer to security best practices for coding, you can review the code of plugins offering similar functionality or if needed, you can take an online course to improve your programming skills.

It is not reinventing the wheel

A lot of people tell you not to write your plugins if someone has already created a plugin with your required functionality as you will be reinventing the wheel.

This logic does not work efficiently in the coding world. Yes, creating an entire CMS like WordPress to host your blog is surely reinventing the wheel. But, adding some code to add functionality may not be the same.

If you are writing code to avoid installing a badly coded or bloated plugin to your WordPress blog, it is a good practice.

If you write a good plugin which works nicely for your WordPress blog and you think that it will be beneficial for a lot of WordPress users, you may decide to release the code publicly by submitting it to WordPress plugin repository.

This way, you can contribute back to the WordPress community and at the same time, it will help you improve your coding skills.

Conclusion

WordPress may be full of a lot of functionality, there may still be many things where it may fall short of your expectations. Though a lot of plugins are available in the WordPress plugin repository, you may not find the plugin which suits your requirements. This calls for writing your custom code and add it to your WordPress blog.

Writing custom code for WordPress may be easy, but you should carefully add your code at the correct place to keep it clean and easily maintainable.

The best way to add your custom code to WordPress is to create a plugin and add it to your WordPress blog.

Do make sure that you follow proper coding standards and best practices. Also, do proper code review and testing to ensure that your code is safe.

Categories
WordPress

How to create a WordPress plugin

In this post, you will learn how to create a simple WordPress plugin without any complex setup or need of FTP/SSH to your hosting server.

Before we begin with this post, let us understand a few things.

I will try to keep the code as simple as possible. My objective in this post is to help you understand how easy it is to create WordPress plugins.

You do not need any FTP or SSH access to your hosting server. All you need is access to your WordPress dashboard with an administrator account with the ability to upload new plugins.

No tools setup is required for creating this plugin. You can write the code in a basic text editor like Notepad which is already included in your Windows computer.

However, I would recommend using a slightly better text editor like Notepad++ which also offers syntax highlighting, but it is completely optional.

No FTP tool is required to upload the code. If you have one and know how to upload, you can try that, but it is not needed at all.

WordPress is amazing

WordPress offers amazing features right out of the box. If you want to create a blog using WordPress, it is as easy as installing software on your Windows computer. There is no coding required.

WordPress makes it so simple. It is a complete blogging system with everything in place to write your next awesome blog.

Let us take a look at some of the basic features of WordPress supported out of the box-

  • Create posts, classify them with categories and tags
  • Upload and manage images, videos, etc. using its built-in media library
  • Define the URL structure of your choice using permalink settings
  • A simple yet fully functional comment system with dedicated comment management dashboard
  • Thousands of free themes to change your blog’s appearance with just a single click
  • Thousands of free plugins to add any additional functionality

There are many more features that I cannot list here, but you got the idea. WordPress is a complete powerhouse for bloggers helping them focus on their content rather than worrying about managing the technicalities.

Why plugins

No matter how comprehensive a particular software is, there may be innumerable cases where some additional functionality is required. The same is the case with WordPress. Though most of the blogging features are included in the core, there may be situations where additional functionality is needed. That’s where WordPress plugins come into the picture.

For example, if you need to add your copyright text in the page footer, you can find and install a plugin that offers that functionality. The plugin may also add settings page to your WordPress dashboard to allow you to configure the plugin settings.

But, what if the plugin you found includes 10 more features which you do not need. Though it will work for you, it will add bloated code to your blog by adding unnecessary additional features which are of no use to you.

In such a scenario, a good option can be to create your plugin. Yes, it is very easy and a much better option if you want to add a small functionality to your WordPress blog.

Before we dive into creating the plugin, there is one thing you need to know- WordPress Hooks.

What are WordPress Hooks

As the name suggests, hooks are small checkpoints within the WordPress code where you can inject your functionality. You can just write a function and connect to the hook and your function will be called every time the hook is executed by WordPress.

For example, WordPress defines a hook called wp_footer‘ which is called by WordPress when it renders the page footer. You can connect your code with this hook to print your copyright notice in the footer.

Hooks are of two types-

  1. Action hooks
  2. Filter hooks

Action Hooks

Action hooks are mainly for executing some code and print it. For example, I already told you about wp_footer. It is called during the creation of page footer during page load and you can print anything you want to the footer by hooking your function to this action hook.

You can also use an action hook to execute some code that has to be executed on each page load. For example, wp_init is an action hook that is executed when WordPress loads the required data before rendering the page. You can hook into this to execute anything you need before the page is sent back to the user.

All you have to do is create a function and tell WordPress to call it whenever wp_footer is executed.

Filter Hooks

Filter hooks are useful if you want to manipulate or modify data within the WordPress functions. For example, the_content is a filter hook that filters the post content to be printed in the post or page. You can hook into this filter, and it will pass the content string to your function. You can modify this value and return the new value which will be taken by WordPress to print the final content on the page.

This understanding is enough to create your first plugin. I will discuss the code in the next section.

The Plugin

We have got a good understanding of WordPress hooks. Now, using this knowledge, we will create a small plugin. To keep things simple, our plugin will simply add some text to the footer of our WordPress blog.

A WordPress plugin can be a single file or it can be a directory with a bunch of files. To keep things simple, our current plugin will be of a single page, with all the code in the same file.

First of all, we need to select a unique name for our plugin file which must not be a clash with the name of any other plugin in the WordPress repository. To ensure that there is no clash, we will prefix our plugin name with our blog’s name. A good file name can be webrosis-footer-printer.php.

You can use the prefix of your name, blog or company. The file name is completely your choice.

Create a file with this name and open it in a text editor.

Every WordPress plugin index file (in case of a directory) or main file (in case of a single-page plugin) must contain header comment with specific header fields as defined by WordPress.

WordPress uses the details provided in this header comment to display plugin’s information in the installed plugins list in the WordPress dashboard.

In the header comment, it is mandatory to define "Plugin name". Everything else is completely optional. As an example, below is a header comment which I have created for our plugin. You can replace the values with your own.

<?php
/**
 * Plugin Name:       Webrosis Footer Printer
 * Description:       Prints custom content in footer
 * Version:           1.0
 * Author:            Abhineet Mittal
 */

There can be more header fields, but for now, this seems enough for our plugin.

The Code

We want to print our custom content to page footer. So, we will hook into ‘wp_footer’ action hook.

We will first write a function to print our custom content and then hook it to wp_footer action through `add_action’ function.

// Function to print copyright notice in footer
function webrosis_print_content_in_footer() {
    echo 'The content on this website is copyright protected. Do not copy. All Rights Reserved.';
}
// Now hook this function to wp_footer action
add_action( 'wp_footer', 'webrosis_print_content_in_footer' );

Save the file.

That’s it. This is the only code you need to write. When added to your WordPress blog, this plugin will print the given content in the page footer.

Here is the complete code-

<?php
/**
 * Plugin Name:       Webrosis Footer Printer
 * Description:       Prints custom content in footer
 * Version:           1.0
 * Author:            Abhineet Mittal
 */

// Function to print copyright notice in footer
function webrosis_print_content_in_footer() {
    echo 'The content on this website is copyright protected. Do not copy. All Rights Reserved.';
}
// Now hook this function to wp_footer action
add_action( 'wp_footer', 'webrosis_print_content_in_footer' );

This plugin will not add any configuration settings to your WordPress dashboard as we have not coded that. However, once you start writing plugins, you can learn about the WordPress Settings API to add your custom settings page in the WordPress admin dashboard.

Installation

You have created your first plugin. Now its time to add it to your WordPress blog. Use the following steps-

  1. Zip this plugin file
  2. Go to your WordPress blog dashboard and click on "Plugins > Add New"
  3. Upload the zipped file of your plugin
  4. Now activate the plugin by clicking on "Activate"

If you have done everything till now exactly as I told you, the plugin will be successfully activated.

Now go to any post or page on your blog frontend and you will find that your content has been added to the footer.

Congratulations! You have successfully created your first WordPress plugin.

So, you saw how amazingly simple it is to create a WordPress plugin. If you want to add small functionalities, it is better to write your small functions and add them to your plugin.

Your plugin can only be installed by uploading the zipped file. It will not be available in the WordPress plugins repository until you submit it.

I have not covered uploading the plugin in the WordPress repository as it is a separate process and requires many more steps. At this level, you must first practice writing plugins. Once you start writing useful plugins, you may consider submitting them to the WordPress plugins repository to be used by the community.

Way forward

In this post, you have learned how to create a WordPress plugin. But our example was a very simple one as it was just to explain to you how a plugin works.

To create more meaningful plugins, you can read about other filters and API functions provided by WordPress. A good starting point is WordPress Documentation.

Here are a few simple ideas which you can implement in your plugin-

  • Add Google Analytics code by hooking into wp_head action
  • Add beautiful author box below the content of your posts by hooking into the_content filter
  • Modify the title of your pages by hooking into ‘wp_title’ filter

You can think of many more ideas as per your blogging requirements.

Conclusion

We created a very simple WordPress plugin that printed some custom content in our blog’s footer. It showed, how easy it is to add small functionalities to your WordPress blog by adding simple code in the form of plugins.

Thanks for reading. I hope you found this post useful.

Categories
WordPress

Enable Gzip compression in WordPress with htaccess

With the advancement of web technologies, you have ready-to-use frameworks for any functionality you want to add to your website or WordPress blog. Just include these framework files to your website and add its features through their easy to use API.

For example, if you want readymade styling for your website, you can use CSS frameworks like Bootstrap or Foundation. Similarly, a lot of Javascript libraries are available to add advanced features to your website, without needing you to code complex functions.

Using these frameworks, developers can create fully functional websites in a short time. All they have to do is to include the framework files to their HTML page, then use its functions to implement the desired functionality.

Similarly, these days, people are more oriented towards visual data. It has become necessary to add a lot of images and videos to their content to attract and engage users. Many times, they also include custom-developed CSS and JS files in addition to all the other resources.

Though this makes the websites better in terms of functionality and aesthetics, adding all these files makes the webpage very heavy and negatively affects the website performance.

In a lot of WordPress themes, each page load requires dozens of additional scripting and styling files in addition to the already included media files.

When a user opens such a website in their browser, the browser immediately starts downloading all the resources from the requested web page and render it for the user. It may include stylesheets, script files, images, videos, etc.

Each request to such files increases the page load time as the user has to wait for the resources to get downloaded. If you have multiple files with huge sizes, it adversely affects your site performance.

Now, if the user is on a high-speed internet connection, this may not be a problem at all. But, you cannot assume that all your users are accessing your website through the best internet connections.

As a simple WordPress user, you may have downloaded or purchased an excellent theme for your blog. You may like the functionality of that theme, but the extra file requests are slowing down your website.

You may not know how to optimize the theme through coding. But, you can optimize your blog for better performance through some simple tweaks at the server level.

Two things can be done to improve your WordPress blog performance. They are browser caching and Gzip compression. You can do this at the server level by simply adding some configuration code to .htaccess file in your website root folder.

Browser Caching ensures that your static resources are cached by the user browser to avoid multiple requests of the same file on different pages. The user will save on bandwidth, and the site load speed will improve.

I have already written a post about Browser Caching where I have provided the required configuration.

Let’s take a look at Gzip compression in this post. Gzip compression speeds up your WordPress website by compressing the resources at the server level using simple .htaccess configuration in Apache server.

Gzip compresses the files to reduce payload. It even compresses the minified CSS and JS files to smaller sizes.

Just add the following code to your .htaccess file.

# BEGIN Compressing

# Compress HTML, CSS, JavaScript, Text, XML and fonts
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
AddOutputFilterByType DEFLATE application/x-font
AddOutputFilterByType DEFLATE application/x-font-opentype
AddOutputFilterByType DEFLATE application/x-font-otf
AddOutputFilterByType DEFLATE application/x-font-truetype
AddOutputFilterByType DEFLATE application/x-font-ttf
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE font/opentype
AddOutputFilterByType DEFLATE font/otf
AddOutputFilterByType DEFLATE font/ttf
AddOutputFilterByType DEFLATE image/svg+xml
AddOutputFilterByType DEFLATE image/x-icon
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/xml

# END Compressing

This code ensures that Apache will compress all the files using Gzip before sending them to the user.

Once you implement this code, check your page speed using Google Page Speed Insights tool. You will notice the improvement in your page speed score.

Even if you are not facing website speed issues, you must implement Browser Caching and Gzip Compression on your website. It is recommended by Google & widely supported by most browsers.

Categories
WordPress

Correct file permissions for WordPress on Apache

File permission is a simple yet complex issue. If you manage a website, you need to ensure that the file permissions are adequate so as to allow users to perform operations on the file and at the same time, you need to ensure that file permissions are strict enough to prevent security and hacking incidents.

Wrong permissions will break your automatic updates. Also, if you run composer, you may struggle as composer should not be run as root or sudo user, and non-root user would need read/write permissions to run composer.

This situation usually arises when you run a website on a self-managed server like the one provided by DigitalOcean or Amazon AWS Lightsail. However, the permissions are equally valid for managed or shared hosting where the host has provided you the SSH access to your files.

In this article, I have provided simple file permissions for your WordPress website hosted on Apache server. These permissions should be sufficient for most of your websites, including those which are not built on WordPress.

Giving the correct file permissions to your WordPress website

To begin with, Apache server runs all the processes requires to read/write the website files & directories. So, we need to provide the ownership of the website files & directories to Apache. As Apache runs as www-data, following command is appropriate to give ownership of your entire website folder to www-data user and group.

In your SSH terminal, run the following command.

sudo chown -R www-data:www-data /var/www/wordpress

Here, I am assuming that your wordpress website root is /var/www/wordpress. You can change it to the directory in which your website is hosted.

Now, we need to give all file permissions (read, write, execute) to owner (Apache server) because server needs to perform read/write operations on files & directories. It will ensure that our website runs smoothly without error.

Giving read/write permissions to www-data is fine for your website to run and auto-update without any errors. But, if you try to SSH into your server as a non-root user, you will not be able to read/write your files inside the wordpress directory.

Also, if you use composer, you need read/write access to website files. As per composer’s official documentation, it is recommended that you should NOT run composer as root or sudo user. You should run composer as non-root user. Same is true for other utilities as well which require read/write permissions in your wordpress directory. This means we need more permissions.

For this, I am assuming you have already created a new user with sudo privileges and have logged in through that sudo user (not root use).

First, add you to the www-data group using the following simple command in your SSH terminal. Remember, you must be logged in as a non-root user, with sudo privileges, as whom you want to run composer.

sudo adduser $USER www-data

Above command adds you to www-data group.

Now give read/write/execute permissions to all the files and folders to both owner and group.

sudo find /var/www/wordpress -type d -exec chmod 770 {} ;
sudo find /var/www/wordpress -type f -exec chmod 660 {} ;

Update: Recently I was facing following error while running these commands-

`find: missing argument to -exec'

I fixed that by adding a slash before the terminating semicolon.

So, the update commands are-

sudo find /var/www/wordpress -type d -exec chmod 770 {} \;
sudo find /var/www/wordpress -type f -exec chmod 660 {} \;

You need to log out and log in again for the new permissions to take effect.

That’s it. You now have the correct permissions.

How to check if your WordPress website has correct file permissions

After setting up file permissions, you must validate the new file permissions. To check this, try the following two things-

  • Run composer and check if there is any permission error.
  • Try uploading a file in the WordPress media library.

If you are able to execute the above two operations successfully without error, your WordPress website has the correct file permissions.

Categories
WordPress

Enable browser caching in WordPress using htaccess

Browser caching is very important for any website as it helps in speeding up the website as well as reduces bandwidth costs.

To enable browser caching on Apache, you must have the required modules enabled.

If you are on a shared host like GoDaddy or HostGator, these modules are already enabled in most cases. So, you can skip the following steps and directly go to the htaccess code given at the end of this post.

In case, you are on a cloud server like DigitalOcean, you may need to enable these modules which can be done in following easy steps.

Open your terminal and run following two commands.

sudo a2enmod headers
sudo a2enmod expires

Now restart the Apache server by running following command.

systemctl restart apache2

It will ask for authentication. Enter your password and Apache will restart.

You have successfully enabled Headers and Expires modules on your Apache server.

Now, open the root folder of your website and create a .htaccess file with the following content.

# BEGIN Webroris.com cache-control
<IfModule mod_expires.c>;
    ExpiresActive on
    ExpiresDefault "access plus 2 days"
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType image/jpg "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    ExpiresByType image/x-ico "access plus 1 month"
    ExpiresByType image/x-icon "access plus 1 month"
    ExpiresByType text/html "access plus 1 seconds"
    ExpiresByType text/xml "access plus 1 seconds"
    ExpiresByType text/plain "access plus 1 seconds"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType text/javascript "access plus 1 month"
    ExpiresByType application/xml "access plus 1 seconds"
    ExpiresByType application/rss+xml "access plus 1 seconds"
    ExpiresByType application/json "access plus 1 seconds"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresByType application/x-javascript "access plus 1 month"
    ExpiresByType application/pdf "access plus 1 month"
  <IfModule mod_headers.c>;
       Header unset ETag
       Header unset Pragma
       Header unset Last-Modified
       Header append Cache-Control "public, no-transform, must-revalidate"
       Header set Last-modified "Tue, 1 Oct 2014 10:10:10 GMT"
  </IfModule>;
</IfModule>;
# END Webroris.com cache-control

And that’s it. You do not have to restart your server now as .htaccess file works in real-time. All the files served from your server will now be cached in the user’s browser as per the expires directive mentioned in the .htaccess file. You may also change these to any value of your liking.