How to get post tags and categories

Many times you might need to display post tags or categories along with the post. This can be achieved by using following code


<?php
echo get_the_tag_list('<p>Tags: ',', ','</p>');
?>

If you are using custom taxonomy, you can use following code


<?php echo get_the_term_list( $post->ID, 'modernquotetaxonomy', 'Tags: ', ', ' ); ?>

Using WP Query for Custom Posts

WP Query can be used to fetch posts as per your requirement. Simple syntax for WP_Query is as below

WP_Query for Custom Posts

  <?php  $args = array(
    'post_type' => 'modernquote',
    'tag' => 'success',       
     'orderby' => 'post_date',
     'order'   => 'ASC');
   
  // Custom query.
  $query = new WP_Query( $args );
   
  // Check that we have query results.
  if ( $query->have_posts() ) {
   
      // Start looping over the query results.
      echo "<ul class='list-group '>";
      while ( $query->have_posts() ) {
          $query->the_post();
      // echo '<a href="' .get_post_permalink() .'"><li class="list-group-item">'. get_the_title() . '</li></a><br>';
      echo '<a href="' .get_post_permalink() .'" class="list-group-item">'. get_the_title() . '</a>';
      }
      echo "</ul>"; 
  }
  // Restore original post data.
  wp_reset_postdata();
  
  ?> 

WP_Query for Custom Posts with conditions

  <?php  $args = array(
    'post_type' => 'modernquote',
    'tax_query' => array(
        array (
            'taxonomy' => 'modernquotetaxonomy',
            // 'field' => 'slug',
            'terms' => 'love hindi',
        )
    ),      
     'orderby' => 'post_date',
     'order'   => 'ASC');
   
  // Custom query.
  $query = new WP_Query( $args );
   
  // Check that we have query results.
  if ( $query->have_posts() ) {
   
      // Start looping over the query results.
      echo "<ul class='list-group '>";
      while ( $query->have_posts() ) {
          $query->the_post();
      // echo '<a href="' .get_post_permalink() .'"><li class="list-group-item">'. get_the_title() . '</li></a><br>';
      echo '<a href="' .get_post_permalink() .'" class="list-group-item">'. get_the_title() . '</a>';
      }
      echo "</ul>"; 
  }
  // Restore original post data.
  wp_reset_postdata();
  
  ?> 

Useful WordPress Functions

WordPress provide may useful functions. Many time we don’t have to reinvent the wheel. Here is quick summary of important functions

 

Function Remark
<?php echo get_theme_root_uri(); ?> This gives theme directory
<?php echo get_template_directory_uri(); ?> This gives parent theme
<?php echo get_stylesheet_directory_uri(); ?> This gives child theme

 

How to Install WordPress multisite

Step#1

First you need to finish installing WordPress.  Please refer to “How to install WordPress” to get started.

Step#2

You need to add following line just above the line /* That’s all, stop editing! Happy blogging. */ inside wp-config.php file.

/* Multisite */
define( 'WP_ALLOW_MULTISITE', true );

Now save wp-config file and login as admin to your WordPress site. Go to tools>Network Setup. This option is not available by default, its visible after you have made above changes in wp-config.php file

You will see following scree:

Now select your multisite option with subdirectory or subfolder as per your requirement. Whether to choose subdirectory or subfolder, its completely dependent on your requirement.

It will take few second to install multisite, once done following screen will appear.

Now add following settings just above the line reading /* That’s all, stop editing! Happy blogging. */ Below code is for subdomain, if you have selected subdirectory, it will be slightly different. Please use whichever code is displayed in your admin section.


define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', true);
define('DOMAIN_CURRENT_SITE', 'localgoingplaces.me');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);

Step#3

You can manually add each site, however when there are multile sites, this ecomes tedious process. This can be automated by using a plugin called nginx helper. Install plugin called as nginx-helper from install plugin section.

nginx-helper settings

You don’t have to network activate this plugin. Simply to go your base site plugin section and activate this simillar to other plugins.

Now to to Network Admin–>Settings–>Nginx Helper”. This option will be available only after you have activated the plugin (No Network activation is needed)

Please select enable nginx map and enable nginx logging

Update file nginx file

You would have already created nginx file while installing WordPress as per “How to install WordPress” post.  Now add following code at the start of nginx file.

Don’t copy below code as is. Use the line displayed in previous step in nginx-helper settings page


map $http_host $blogid {
default 0;
include /var/www/wordpressmultisite1/wp-content/uploads/nginx-helper/map.conf;
}

Also if you are planning to use subfolder option, please add following code just before closure of sever block


if (!-e $request_filename) {
    rewrite /wp-admin$ $scheme://$host$uri/ permanent;
    rewrite ^/[_0-9a-zA-Z-]+(/wp-.*) $1 last;
    rewrite ^/[_0-9a-zA-Z-]+(/.*\.php)$ $1 last;
}

Now your multi-site is ready for the use

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 install wordpress on Ubuntu 16.04

Here is quick reference that I created for myselft for creating local wordpress blog installation. Hoep it helps you as well.

  • Installation

Make sure you have following softwares installed on your local machine

  1. MySQL
  2. NGINX
  • Configure MySQL

Create user for wordpress

mysql -u root -p
mysql> CREATE DATABASE localwordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
mysql> GRANT ALL ON localwordpress.* TO 'localwordpresssuser'@'localhost' IDENTIFIED BY 'password';
mysql> FLUSH PRIVILEGES;
mysql> exit;
  • Download  WordPress.

curl -O https://wordpress.org/latest.tar.gz
tar xzvf latest.tar.gz
cp wordpress/wp-config-sample.php wordpress/wp-config.php
mkdir wordpress/wp-content/upgrade
sudo cp -a wordpress  /var/www/wordpress1

After moving WordPress folder to required path, you need to change few folder permissions.

sudo chmod g+w /var/www/html/wp-content
sudo chmod -R g+w /var/www/html/wp-content/themes
sudo chmod -R g+w /var/www/html/wp-content/plugins
sudo chown -R www-data:www-data /var/www/html
  • Configure WordPress

Open wp-config.php file and make following changes

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'localwordpress');

/** MySQL database username */
define('DB_USER', 'localwordpresssuser');

/** MySQL database password */
define('DB_PASSWORD', 'password_here');

/** MySQL hostname */
define('DB_HOST', 'password');

/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');

Visit following link for generate AUTH KEY and other remaining fields

https://api.wordpress.org/secret-key/1.1/salt/

simply copy paste values displayed on above link  into config.php file at appropriate location. Here is the sample. (Please don’t copy paste below values into your installation)

define('AUTH_KEY',         'Johd+fp5c.esU?J26hZb8^6Gi GAL+^Abs-{k4%g0G4IEGVKlZ`|MEk4B;W++%s*');
define('SECURE_AUTH_KEY',  '_J}pBRjcek6f+wj*BNF}lPu-xNX$^.+`nIx|*kg-YjY+v)%Qi<J`pI?|zE/BIa<U');
define('LOGGED_IN_KEY',    '2.T%wJpUwsSeZQV?K,R)7$u }yl]rfLt|.gg,uI.SP&U>u_7q+*uH2+Gy4}-AmYC');
define('NONCE_KEY',        '~^T R=oy/Ej`>q8&FP7rPM1vZ%;}*@oz7^b~~>>Clw{.LGYdbDjV$-t<U5/(&;M7');
define('AUTH_SALT',        'Nn?`[;?9=niA=Jun:ikXi(BR%%Y7MYVtMd+,a&_ZKQei3S ;Z8XteX{=f8~~=D~p');
define('SECURE_AUTH_SALT', 'WCRf7Un/.BX9z~_4dt}!-k$<Y02mm=fKEvHo;5{]!s9=w/x/@9-,Q?ib-jMM#47/');
define('LOGGED_IN_SALT',   '$~+K5U>rd3_B#+X*^G2hlBTnD:)W](rer%VMS #G8jJ^f(5Gr@.aF:6`hg~:OkS(');
define('NONCE_SALT',       'xdtH,{ir(-I5|/NIHaD^eFu.pKCIC-5!Gn`YBDq#?bRfhI5,-c,;?^^<6V%P04iD');

Also add FS_METHOD  after “define (‘WP_DEBUG’, false);”. It should look as below

define('WP_DEBUG', false);
define('FS_METHOD', 'direct');
  • Troubleshooting

I got error “Authentication is needed to run ‘/bin/cp’ as the super user” while saving wp-config.php file.

Its not a big deal. Simply go to terminal and run following commands

sudo chmod 777 projectname
sudo chown $USER -R projectname/
  • Configure nginx

  • You need to configure nginx so that typed url will direct to correct installation directory. Following is the sample code. You can copy this as is but make sure you change the server_name parameter to your domain name.Create following file in folder /etc/nginx/sites-available/. You name is as you with but for easy reference, add name of domain in the file name.
    server {
    listen 80;
    listen [::]:80;
    
    root /var/www/wordpress1;
    index index.html index.htm index.nginx-debian.html;
    
    server_name localwordpress1.com www.localwordpress1.com;
    
    location / {
    #try_files $uri $uri/ =404;
    # original content
    try_files $uri /index.php$is_args$args;
    #try_files $uri $uri/ /index.php$is_args$args;
    }
    
    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    
    # With php7.0-cgi alone:
    #fastcgi_pass 127.0.0.1:9000;
    # With php7.0-fpm:
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }
    
    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    # deny all;
    #}
    }

    copy this file to sites-enabled folder using following command and restart nginx

    $sudo ln -s /etc/nginx/sites-available/wordpress1.com /etc/nginx/sites-enabled/
    $sudo nginx -t
    $sudo systemctl restart nginx

    Considering we need to access local installation on custom url, that url need to point to localhost. This needs to be changed in host file.

    sudo nano /etc/hosts
    127.0.1.1 localwordpress1.com
  • Access your installation # localwordpress1.com
install wordpress ubuntu 16.04
install wordpress ubuntu 16.04