How to selectively dequeue a script on individual post

Lot of plugins. Not sure what to do??

All of a sudden you may realise that you already have quite a lot of plugins on your website and probably some of those plugins are slowing your site down. That’s the point of time you may decide to review your plugins but at that point it is very difficult to imagine the impact of deactivating a certain plugin.

Here is a simple trick we can use to review our plugins and make sure atleast our important pages do not break.

Idea

The idea is to try and dequeue or remove a script on a page by page basis or post by post basic. Using this approach we are not deactivating the plugin on the entire site but we are just deactivating or removing it on just a single post or page. This way we can study the impact of removing the plugin on our most important pages/posts just so that we are sure it won’t break our site and we feel more comfortable to deactivate the plugin entirely on our site.

So how do we achieve this

Step 1: Print all the script handles used on a page/post

Step 2: Create a custom field

Create a custom field named wpi_selective_scripts_dequeue on our post/page and add bar separated (|) handles of the scripts which you wish to remove from the page (referring to list generated in step 1)

Step 3: Dequeue the script for that page/post

 

 

 

 

How to add custom checkout fields to WooCommerce order

Follow below steps to add custom checkout fields to WooCommerce.

Scenario: We want to create a new address field named as territory. It will be a drop down field and will be used to decide the shipping cost.

Create the new field/s on the checkout page

To create a similar field in shipping address, $fields array would need to be duplicated mentioning [‘shipping’] instead of [‘billing’]

Now let us understand the parameters used in the above code

Hook: Creating a new field uses woocommerce_checkout_fields hook

type: Since this an drop down field the type of the field is select. If you want a mobile number field it could be a text field

required: specify whether the field is compulsory or not. In our case we are calculating the shipping cost based on this field so it is compulsory.

class: 

  1. form-row-wide: The new field will occupy the entire div width for the billing section
  2. form-row-first: The new field will appear in the first half area of the row (like the first name field)
  3. form-row-last: The new field will appear in the last half area of the row (like the last name field)
  4. address-field: specifies that it is an address field
  5. update_totals_on_change: Since we want to update the shipping price on the checkout page based on this field this class triggers the ajax update process on field value change
  6. options: Drop down field options can be provided using this parameters. Obviously this field will not be applicable for text box

Validate the newly created field

Here we are just specifying the error message to display when the field is left empty

Save the field data

Here we are saving the data to the postmeta table for the corresponding order_id after the form is submitted

Show the custom field value on the orders page under billing section

 

How to create wordpress options page

Creating WordPress options page in Dashboard for your own plugin is quite simple. Generally it is used to set global preferences for your plugin which you want to let the users customise as per their requirement.

We will create a settings screen by creating a class as that is the simplest way of creating your own options page for your custom plugin.

It can be done in 5 simple steps

  1. Declare Class for the settings Page
  2. Add the page in the settings menu
  3. Register your settings
  4. Create the backend options
  5. Finally generate the options page

Here is the entire code

Now we will discuss each function in detail

First of all we have named our class as someCustomPluginSettings

The constructor just calls the add_admin_menu function and initialises the settings registration

Below function creates the admin page.

Here we need to provide

  • Title of the settings page
  • Capability (this decides who will get access to this page). manage_options means editors and above can access this page.
  • Slug of the page

Below function registers the settings variables, description on the settings page, etc. The most important variable here is some_custom_plugin_settings. We will be using this variable to reference our stored data using the settings screen.

Below function creates the HTML objects to store our data. Please note that each field uses the same reference i.e.

some_custom_plugin_settings and stores the data in array i.e.

some_custom_plugin_settings[‘setting_1’], etc

Below function just renders the options page in a form

 

 

WordPress admin custom column sorting and filtering for custom post type

In WordPress Dashboard there are some default columns listed for any of your post types on the post listing page. We can sort our custom posts by Ascending or Descending order by just clicking these fields. However most of the times these fields are not enough.

E.g. if we create a custom post for books then we may need columns to sort or filter books by Year of publication, Author, Category, etc

So how do we create these extra columns for sorting and filtering

Assumptions

  1. Custom Post Type: book
  2. Year,  Author and Language information is stored in custom meta fields for each book

Se here are the steps

Step 1: Define the custom colums

Here we add two new columns to the admin panel of the custom post type book namely Publication Year and Author

Step 2: Fill Data to the columns

Here we are assigning data to the columns displayed in the custom post. Since the data is stored in the post meta we use get_post_meta function to get the data from the postmeta table.

Step 3: Define sortable colums

Here we are defining which columns are sortable. In our case we want all the columns to be sortable.

Step 4: Perform Sorting

Here we are using the request filterThis filter is applied to the query variables that are passed to the default main SQL query of the page. This filter adds additional parameters/filters to the query variable based on which the list of posts gets generated.

Until this step the additional columns are added to the custom post type listing page and they are sortable. They can be sorted by clicking the table heading as shown below

Additional columns

 

Step 5: Create Filters

This part of code can vary depending upon our configuration of custom fields and taxonomy. Main objective here is to create select boxes for the filters. Below approach shows how to create select boxes for data stored in custom meta fields. If the data is stored is categories then we may need to use wp_dropdown_categories function to list categories for the filter

Step 7: Perform Filtering

Here we are just altering the main query for the page by passing our own variables.

This will create filters as shown below

Custom Filter admin screen

How to create custom post type template files in wordpress

Any wordpress theme comes with a single post, page and archive template. None of these templates may be suitable for you if are creating your own custom post for event, products, etc.

In such cases we need to create our own templates

There are 2 ways to create custom post type template files in wordpress

Method 1: Create custom post type template files within your Child Theme folder

Suppose your custom post type is event. You would create below files in your child theme directory.

  • single-event.php
  • archive-event.php

Once the above files are created they will be automatically picked for your events single post and archive posts. So whatever your custom post type is, the template file names should be as named as below

  • single-{post-type}.php
  • archive-{post-type}.php

Refer WordPress Theme Handbook

Advantages:

It is very easy to create and modify your custom post type template files

Disadvantages:

  1. The template files are not within your plugin. So if you want to install the plugin on some different website you need to remember to get the template files from the theme directory as well.
  2. If later you do not want this plugin anymore then disabling the plugin is not sufficient. You need to remove the above template files from the themes directory.
  3. This method can get messy as later it becomes difficult to remember why certain templates were created (unless you properly document them).

 

Method 2: Create custom post type template files in your plugin folder

This is assuming you have created your custom post by creating a plugin for it. (Note: Ideally a custom post should be created using a plugin anyway due to various advantages of plugins).

In this method copy the single.php and archive.php files from your themes directory and paste them in your plugin directory. If you wish you can create a subfolder named as templates inside your plugin and paste this files in the templates subfolder.

Now add below code in your plugin file

Advantages

  1. All your code related to the custom post remains in a single directory. So it is much easier to maintain.
  2. You can move the plugin folder anywhere along with the templates
  3. Becomes easier to activate or deactivate a plugin

 

How to change default RSS feed posts limit

By default RSS feed in WordPress shows 10 posts. This default count can be changed by adding below code in your functions.php file

In above code the limit is increased to show 20 posts

How to create extra widget/sidebar areas

Depending upon your theme you may have some predefined widget/sidebar areas like Left Sidebar, Right Sidebar.

If you want to create a new sidebar area let’s say for footer then you can add below code in your functions.php file

Replace THEME_NAME with the name of your theme

Finally add below code in the theme where the sidebar needs to appear

 

WordPress Security – Configuration / Installation

Wordpress Security
Photo credit – 2508581015littleblackcamera

1. WordPress security at the Configuration and installation level

This section explains measures to be taken for achieving wordpress security while installing and configuring wordpress.

1.1 Change default table prefix

Many published WordPress-specific SQL-injection attacks make the assumption that the tableprefix is wp, the default. Changing this can block at least some SQL injection attacks.

1.2 Securing wp-config.php

Are you aware that wp-config.php can be stored one directory level above the WordPress installation?

This is quite a simple task. Also, make sure that only you (and the web server) can read this file (it generally means a 400 or 440 permission). This file contains quite sensitive information like password, database user etc so it’s very imp to protect this file

1.3 Disable File Editing through WordPress Dashboard

The WordPress Dashboard by default allows administrators to edit PHP files, such as plugin and theme files. This is often the first tool an attacker will use if able to login, since it allows code execution. WordPress has a constant to disable editing from Dashboard.

Add below line in wp-config.php

1.4 Blocking Search Engine Spiders from Indexing the Admin Section

Search engine spiders crawl over your entire blog and index every content. Using robots.txt file we can restrict the content which we would like to be indexed by Search engines. Obviously the admin section is not required to be indexed. Just create a file named robots.txt in your root folder (generally public_html) folder and paste below contents in that file.

#
User-agent: *
Disallow: /cgi-bin
Disallow: /wp-admin
Disallow: /wp-includes
Disallow: /wp-content/plugins/
Disallow: /wp-content/cache/
Disallow: /wp-content/themes/
Disallow: */trackback/
Disallow: */feed/
Disallow: /*/feed/rss/$

1.5 HTTPonly cookie

This prevents the cookie to be accessed by any Javascript

Add below in your htaccess file.

php_flag session.cookie_httponly On

Reference: OWASP XSS Bonus Rule SQL injection

1.6 Subscriber account

Login with a  subscriber account regularly to check of any of your plugins have created any unnecessary administrative links which are not supposed to be accessed by subscribers

1.7 Keep your wordpress and plugins uptodate with latest versions

Latest wordpress version mostly has fixes related to recent security vulnerabilities. It is very important to update your wordpress installation as soon as a new version is released. The same follows for plugins. However plugins security is mostly upto the author so it is very important to select a secure plugin.

1.8 Change the default login URL

WordPress default login URL is http://www.yoursite.com/wp-login.php

A hacker who wants to break in to you site typically uses Brute Force technique on this URL. Brute Force in this case means a script which will automatically try various usename/password combinations on your login URL. You would think that you are safe because your firewall is set to track this particular activity and would just block the IP. Howerver the hackers are one step ahead. They keep trying this script from various IPs. So if one IP is blocked the script automatically runs from a different IP. Also the script is set to run at regular intervals to avoid any DDoS alarlms

To avoid such scripts attacking your login page, just change/redirect your login page to some secret page e.g. http://www.yoursite.com/entermysite. That way you would protect yourself from such automated scripts trying to Brute Force your authentication.

To change your login page just install the plugin Rename wp-login.php and on the settings page on this page provide your new URL.

WordPress – remove emoji code introduced by 4.4

If you are on WordPress 4.4 or more you may have noticed the emoji related code in your source code.

If you do not need this code just add below lines in your theme’s functions.php

 

12