How to add custom css file in WordPress?

One of the best thing about CSS is plug-able components, however this comes with following certain way of WordPress. Adding CSS from external files.

Adding Bootstrap CSS and JS files to WordPress


function my_scripts_enqueue() {

wp_register_script( 'jquery-slim-js', 'https://code.jquery.com/jquery-3.3.1.slim.min.js', array('jquery'), NULL, true );
wp_register_script( 'popper-js', 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js', array('jquery'), NULL, true );
wp_register_script( 'bootstrap-js', 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js', array('jquery'), NULL, true );
wp_register_style( 'bootstrap-css', 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css', false, NULL, 'all' );
wp_enqueue_script( 'jquery-slim-js' );
wp_enqueue_script( 'popper-js' );
wp_enqueue_script( 'bootstrap-js' );

wp_enqueue_style( 'bootstrap-css' );
}
add_action( 'wp_enqueue_scripts', 'my_scripts_enqueue' );

Adding custom CSS file to WordPress theme.

Now let us create a folder called css inside theme folder “twentyseventeen”. Following is the code to custom “carousel.css file.


function my_scripts_enqueue() {

wp_register_script( 'jquery-slim-js', 'https://code.jquery.com/jquery-3.3.1.slim.min.js', array('jquery'), NULL, true );
wp_register_script( 'popper-js', 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js', array('jquery'), NULL, true );
wp_register_script( 'bootstrap-js', 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js', array('jquery'), NULL, true );
wp_register_style( 'bootstrap-css', 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css', false, NULL, 'all' );
wp_register_style( 'carousel-css',get_template_directory_uri().'/css/carousel.css', array() );

wp_enqueue_script( 'jquery-slim-js' );
wp_enqueue_script( 'popper-js' );
wp_enqueue_script( 'bootstrap-js' );

wp_enqueue_style( 'bootstrap-css' );
wp_enqueue_style( 'carousel-css' );
}
add_action( 'wp_enqueue_scripts', 'my_scripts_enqueue' );

Adding custom CSS toWordPress child theme

But if you are using child them above will not work, you need to use following. Please note that, you need to useget_stylesheet_directory_uri() instead of get_template_directory_uri()


function my_scripts_enqueue() {

wp_register_script( 'jquery-slim-js', 'https://code.jquery.com/jquery-3.3.1.slim.min.js', array('jquery'), NULL, true );
wp_register_script( 'popper-js', 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js', array('jquery'), NULL, true );
wp_register_script( 'bootstrap-js', 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js', array('jquery'), NULL, true );
wp_register_style( 'bootstrap-css', 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css', false, NULL, 'all' );
wp_register_style( 'carousel-css', get_stylesheet_directory_uri().'/css/carousel.css', array() );

wp_enqueue_script( 'jquery-slim-js' );
wp_enqueue_script( 'popper-js' );
wp_enqueue_script( 'bootstrap-js' );

wp_enqueue_style( 'bootstrap-css' );
wp_enqueue_style( 'carousel-css' );
}
add_action( 'wp_enqueue_scripts', 'my_scripts_enqueue' );

How to use PRISM.JS syntax highlighter with WordPress

Prism.js is one of the most widely used tool for syntax highlighing. I have been using Crayon Syntax Highlighter for a while but in some cases, I am not happy with the result. When I was using ghost bloging platform, I was using PRISM.JS and output was very satisfying. so I decided to give it a another try.

There are few plugins but I was none of them look promising so I decided to add PRISM.JS to my wordpress site the crude way.

Step#1 Download prism javascript and css files. You can customize whichever language you want to use and download file size will vary accordingly.

select development or  version along with the required languages.

download prism.js and prism.css files. Please note the size of the files based on the languages that you have selected.

Step#2 Copy prism.js and prism.css files to your themes public files folder and add following function


function my_scripts_enqueue() {

wp_enqueue_style ('prism-css', get_theme_file_uri().'/css/prism.css');
wp_enqueue_script ('prims-js', get_theme_file_uri().'/js/prism.js');

}
add_action( 'wp_enqueue_scripts', 'my_scripts_enqueue' );

Step#3 Using the prims.js

For using primsjs, you need to go to “Text” section of any post and add code inside below tags. Also, you need to menstion name of the language in class.


<pre><code class="language-markup">
//Some html stuff here
</code></pre>

If you are already using “Crayon Syntax Highlighter”, you need to disable it before prims.js to take effect.

 

How to add Drop Caps in WordPress without using any plugins

WordPress has plugins for anything that you need to do. Even if you don’t know any coding, you can create wonderful website, however, adding too many plugins clutter your WordPress website.

Also, having too many plugins can cause slowness in your WordPress website and some plugins can misbehave because of interfernce from some other plugin.

Having dropcaps is very basic requirement and I dont think you need to use plugin for this. You can simply copy past following css in Customize->Additional CSS

div.entry-content p:first-child:first-letter {
float:left;
font-size:2.5em;
color: inherit;
margin-right:0.10em;
line-height:90%;
}

 

How to set up Static Front Page with WordPress

By default, WordPress shows the latest posts, but what if you wanted the homepage of your website to display the same page every time. This “static front page” look is common for users desiring static or welcoming information on the front page of the site.

There are two ways to add Static Front Page

  1. Go to the Pages > Add a New Page dashboard page. This option is on the left sidebar in your WordPress Dashboard.
    Name the page “Home” and type whatever you want for the content your homepage.
  2. Create a template called as front-page.php and add whatever you want to add here. This can be static or dynamic as per your needs.
  3. Add another page called “Blog” and leave the content of the page as blank.
  4. Now go  to the Settings > Reading Settings dashboard page.WordPress Static Page Settings
  5. By default :Your Latest posts is chosen. Select “A Static Page (Choose Below)”.
    For “Front Page”, choose the “Home” page you just created.
    For “Posts Page”, choose the  “Blog” page you created.

That’s all, your static page along with normal log page is created.

Let’s have a look at second approach.

  1. Create a new template in WordPress file directory and name it as home.php . Due to naming convention and prioritization, home.php will be provided priority over index.php. Here is simplest home.php .
    <?php
    /**
    Template Name: Home Page
    */
    get_header(); ?>
    <p>Add any functionality here. This is new blog home p</p>
    <?php
    get_footer();?>

     

  2. Copy index.php into new file called as blogindex.php and add following lines at the top of the file.
    <?php 
    /** 
    Template Name: Blog Index Page 
    */
    ?>

    Here, you would need to add WP_Query as well.

  3. Create a page called as “blog” and assign a template “Blog Index Page” to it. Please not that, in this approach, you don’t have to make any changes in  Settings > Reading

Once above is done, your static home page along with blogs page is ready.

How to add Bootstrap to WordPress Themes

I created child theme using tweentyseventeen, you can follow the steps here. Once I created child theme, I found that I need to create some layouts and to create it, I would have have to write some CSS from scratch.

But when you have amazing tools like bootstrap, why do we need to write css from scratch.

But how to add bootstrap to WordPress theme ?

You can simple add css and js files in head and footer files but that’s not the proper way. You can add bootstrap to your theme by adding following code to functions.php file of your child theme

function my_scripts_enqueue() {

wp_register_script( 'popper-js', 'https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js', array('jquery'), NULL, true );
wp_register_script( 'bootstrap-js', 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js', array('jquery'), NULL, true );
wp_register_style( 'bootstrap-css', 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css', false, NULL, 'all' );

wp_enqueue_script( 'popper-js' );
wp_enqueue_script( 'bootstrap-js' );

wp_enqueue_style( 'bootstrap-css' );
}
add_action( 'wp_enqueue_scripts', 'my_scripts_enqueue' );

Once done you can see bootstrap in your webpage’s source code. You can start using bootstrap class in your template files.

How to Create a WordPress Child Theme

Creating child theme is one of the best options provided by WordPress ecosystem. By using child theme you can utilize features provided by parent theme along with customization that you want to do. And the best part is that, you do not loose any further updates to parent theme.

WordPress theme such as tweenty seventeen, twenty fifteen have been developed and tested by hundreds are developer and it makes no sense to reinvent the wheel. You can simply use the well tested wheel and modify as per your needs.

Please follow below steps for creating child themes

Step#1 Create Basic Structure

A child theme consists of at least one directory (the child theme directory) and two files (style.css and functions.php), which you will need to create:

Create a folder and name it as required. I have created a child theme of ‘twentyseventeen’ so I created folder name ‘twentyseventeen-child’

Step#2 Update style.css

Copy following code in style.css. Please note to change child theme name as required.

/*
Theme Name: twentyseventeen-child-fintrekking
Theme URI: 
Description: twentyseventeen-child-fintrekking
Author: Pravin Jagtap Deshamukh
Author URI: http://example.com
Template: twentyseventeen
Version: 1.0.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: fintrekking
Text Domain: twentyseventeen-child-fintrekking
*/

The Template line corresponds to the directory name of the parent theme. The parent theme in our example is the Twenty Seventeen theme, so the Template will be twentyseventeen. You may be working with a different theme, so adjust accordingly.

Updating function.php

If you use child theme at this point of time, it will load something like below. This is due to the fact that child theme is not yet importing parent style.css

WordPress Child theme CSS not loaded error

Step#3 Update functions.php

You can import parents style two two methods

  1. Using @import in child themes style.css
  2. Using function.php

Using function.php is recommended method and we will use the same.

<?php
function my_theme_enqueue_styles() {

$parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.

wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>

Note: Please make sure you add correct parent style. Here you need to replace word parent with parent theme name.

e.g.

$parent_style = 'twentyfifteen-style'
$parent_style = 'twentyseventeen-style'

Old way of including style.css is by adding following code in child themes style.css. This is not a recommended method but it works. Add import statement right after template definition as shown below

/*
Theme Name: twentyseventeen-child-fintrekking
Theme URI: 
Description: twentyseventeen-child-fintrekking
Author: Pravin Jagtap Deshamukh
Author URI: http://example.com
Template: twentyseventeen
Version: 1.0.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: fintrekking
Text Domain: twentyseventeen-child-fintrekking
*/

@import url("../twentyseventeen/style.css");

Once this is updated, you can see the theme CSS is loaded properly.

WordPress Child theme CSS working properly

Step#4 changing other php files

Your child theme can override any file in the parent theme: simply include a file of the same name in the child theme directory, and it will override the equivalent file in the parent theme directory when your site loads. For instance, if you want to change the PHP code for the site header, you can include a header.php in your child theme’s directory, and that file will be used instead of the parent theme’s header.php.

You can also include files in the child theme that are not included in the parent theme. For instance, you might want to create a more specific template than is found in your parent theme, such as a template for a specific page or category archive.

Special case of functions.php

Unlike style.css, the functions.php of a child theme does not override its counterpart from the parent. Instead, it is loaded in addition to the parent’s functions.php.

In that way, the functions.php of a child theme provides a smart, trouble-free method of modifying the functionality of a parent theme.

How to add table in WordPress post

May times we run into a situation where we feel presenting some inforation will be easy to understand if its presented in a tabular manner however, wordpress editor does not have any feature to add table in a post. You can add table in a post by two ways

  1. Using WordPress plugin TinyMCE Advanced
  2. Create a post using table html tags

Using WordPress plugin TinyMCE Advanced

If you are not comfortable with coding then this is the best method. Even if you are comfortable with coding html, this plugin is so user freindly that you will love to use it.

Go to Plugins->Add New and search using “TinyMCE Advanced”. You will find “TinyMCE Advanced” by “Andrew Ozz”. Simply install and activate it.

Your create post window will have many more options along with insert table.

TinyMCE Advanced

Create a post using table html tags

 

Use this option if you are confortable with coding and you dont want to clutter your WordPress installation with multiple plugins. If you are advance user of wordpress, you will have 10-20 plugins installed for various activities. Sometimes plugins interfere with each others functions and system might behave unexpectedly. To avoid this, you can simple use code

Here is sample code with one head and two rows

Important Note: You need to copy this code by going into “TEXT” mode of the WordPress editor, otherwise, this table will not render and you will see html on the post

<table>
<tbody>
<tr>
<td style="width: 218.609px;"><strong>Remark</strong></td>
<td style="width: 345.609px;"><strong>API URL</strong></td>
</tr>
<tr>
<td style="width: 218.609px;">This provides last 10 latest posts</td>
<td style="width: 345.609px;">https://www.techtrekking.com/wp-json/wp/v2/posts</td>
</tr>
<tr>
<td style="width: 218.609px;">This provides last 10 latest posts</td>
<td style="width: 345.609px;">https://www.techtrekking.com/wp-json/wp/v2/posts</td>
</tr>
</tbody>
</table>

and this will render as below

Remark API URL
This provides last 10 latest posts https://www.techtrekking.com/wp-json/wp/v2/posts
This provides last 10 latest posts https://www.techtrekking.com/wp-json/wp/v2/posts

Getting started with WordPress REST API

REST APIs are a growing technique and a big opportunity for developers. Knowing how to create APIs and how to consume them gives you a great advantage. A REST API can be consumed everywhere. On mobile applications, on front-end (web apps) or any other devices that have access on the net.

 

Remark API URL
This provides last 10 latest posts https://www.techtrekking.com/wp-json/wp/v2/posts
Retrieve post using post ID https://www.techtrekking.com/wp-json/wp/v2/posts/154
This provides 10 categories https://www.techtrekking.com/wp-json/wp/v2/categories
Retrieve specific categories https://www.techtrekking.com/wp-json/wp/v2/categories/34
Get all tags https://www.techtrekking.com/wp-json/wp/v2/tags
Get Specific tag https://www.techtrekking.com/wp-json/wp/v2/tags/20
List of pages https://www.techtrekking.com/wp-json/wp/v2/pages/2
Users https://www.techtrekking.com/wp-json/wp/v2/users
specific user https://www.techtrekking.com/wp-json/wp/v2/users/1

How to setup cron job for Let’s Encrypt SSL renewal

Lets encrypt is great tool. It provides free SSL certificate but this certificate comes with validity of 90 days  and to make sure you do not run out of SSL certificate validity, you need to renew SSL certificate every 90 days.

As per this post from Lets Encrypt forum, it will process renewal request 30 days prior to date of expiration so it make sense to schedule a cron  job which will run every month to ensure all certificates are valid all the time.

Open cronjob file using following command

sudo crontab -e

When you run this command for the first time, it will ask you to choose editor

no crontab for root - using an empty one

Select an editor. To change later, run 'select-editor'.
1. /bin/ed
2. /bin/nano <---- easiest
3. /usr/bin/code
4. /usr/bin/vim.tiny

Choose 1-4 [2]:

You can choose any editor that you are comfortable with. I chose second option. It will open file having following content.

#Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command

add following line at the end and save it. (This will run cron job @ 00:00 hr on 1st of every month)

0 * 1 * * /usr/bin/certbot renew --quiet --pre-hook "/bin/systemctl stop nginx" --post-hook "/bin/systemctl start nginx"

That’s it, you are all set.

You can use cron job tool https://crontab.guru/ to cross check the schedule

cron schedule expressions

There are 5 elements in schedule

  • 1st * represents minute
  • 2nd * represent hour
  • 3rd * represent day of the month
  • 4th star represent month
  • 5th star represent day of the week.

e.g.

When Syntax
Every day at 9 AM 0 9 * * *
Every day at 9:05 AM 5 9 * * *
Every day at 07:00 PM/ 19:00 0 19 * * *
Only on monday @ 19:00 0 19 * * 1
Only on 1st of every month @ 19:00 0 19  1 * *

For more permutations and combinations, please refer to https://crontab.guru/

Verification.

To check if this is working, you can change schedule as below (It will run cronjob every minute.

* * * * * /usr/bin/certbot renew --quiet --pre-hook "/bin/systemctl stop nginx" --post-hook "/bin/systemctl start nginx"

 

How to check cron job logs

sudo grep CRON /var/log/syslog

This will show the logs as below

May 1 11:56:01 ubuntu-512mb-server CRON[8519]: (root) CMD (/usr/bin/certbot renew --quiet --pre-hook "/bin/systemctl stop nginx" --post-hook "/bin/systemctl start nginx")
May 1 11:57:01 ubuntu-512mb-server CRON[8594]: (root) CMD (/usr/bin/certbot renew --quiet --pre-hook "/bin/systemctl stop nginx" --post-hook "/bin/systemctl start nginx")
May 1 11:58:01 ubuntu-512mb-server CRON[8616]: (root) CMD (/usr/bin/certbot renew --quiet --pre-hook "/bin/systemctl stop nginx" --post-hook "/bin/systemctl start nginx")
May 1 11:59:01 ubuntu-512mb-server CRON[8624]: (root) CMD (/usr/bin/certbot renew --quiet --pre-hook "/bin/systemctl stop nginx" --post-hook "/bin/systemctl start nginx")
May 1 12:00:01 ubuntu-512mb-server CRON[8631]: (root) CMD (/usr/bin/certbot renew --quiet --pre-hook "/bin/systemctl stop nginx" --post-hook "/bin/systemctl start nginx")

If you are running into any issues, please do let me know

How to add SSL and HTTPS to WordPress

SSL certificates makes your website more trustworthy to readers and it highly likely that your will spend more time or trust your content more when he sees ‘Secure’ in green in address bar. Not just this, search engine provider give higher rank to secure sites as compared to non secure websites. You can follow below steps to make your WordPress website “Secure” at not extra cost.

Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free TLS/SSL certificates,

Step#1 Install Certbots

sudo add-apt-repository ppa:certbot/certbot

Update packages

sudo apt-get update

Install certbost nginx package

sudo apt-get install python-certbot-nginx

Step#2 Configure NGINX

Most likely this is already configured. Just ensure your host names are updated corrected as below.

server_name example.com www.example.com;

Verify NGINX syntax and restart it.

sudo nginx -t

sudo systemctl reload nginx

Step#3 Allow HTTPS through firewall.

sudo ufw allow 'Nginx Full'

Once this is done, you can check what all is allowed

sudo ufw status

Step#4 Obtain SSL Certificate.

Use following command to obtain SSL certificate. It will ask for email ID where notifications will be sent.

sudo certbot --nginx -d example.com -d www.example.com
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel):

Once your enter email ID and hit enter, it will ask for few usual confirmations.

Starting new HTTPS connection (1): acme-v01.api.letsencrypt.org

-------------------------------------------------------------------------------
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v01.api.letsencrypt.org/directory
-------------------------------------------------------------------------------
(A)gree/(C)ancel: A

-------------------------------------------------------------------------------
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about EFF and
our work to encrypt the web, protect its users and defend digital rights.
-------------------------------------------------------------------------------
(Y)es/(N)o: Y

Once this is done, it will ask about redirect . Please find below sample example for this site.

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
Starting new HTTPS connection (1): acme-v01.api.letsencrypt.org
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for techtrekking.net
http-01 challenge for www.techtrekking.net
Waiting for verification...
Cleaning up challenges
Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/techtrekkingnet
Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/techtrekkingnet

Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
-------------------------------------------------------------------------------
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
-------------------------------------------------------------------------------
Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2
Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/techtrekkingnet
Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/techtrekkingnet

-------------------------------------------------------------------------------
Congratulations! You have successfully enabled https://techtrekking.net and
https://www.techtrekking.com

You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=techtrekking.net
https://www.ssllabs.com/ssltest/analyze.html?d=www.techtrekking.net
-------------------------------------------------------------------------------

IMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at:
/etc/letsencrypt/live/techtrekking.net/fullchain.pem
Your key file has been saved at:
/etc/letsencrypt/live/techtrekking.net/privkey.pem
Your cert will expire on 2018-07-30. To obtain a new or tweaked
version of this certificate in the future, simply run certbot again
with the "certonly" option. To non-interactively renew *all* of
your certificates, run "certbot renew"
- If you like Certbot, please consider supporting our work by:

Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate
Donating to EFF: https://eff.org/donate-le

 

Step#5 Configuring WordPress

Once you have this these changes, making sure your WordPress is compatible with this changes is must. Although  I did not face any issue even after not making changes in WordPress, I recommend you do it.

WordPress Address Configuration for SSL

Although it is not mandatory, please restart your NGINX server. Once done, when you access your website, you will see “Secure” in green. Just like below.

WordPress SSL

This SSL certificate is valid for 90 days, please refer to this post to see how to set up cron job renewal of Let’s Encrypt SSL Certificate