How to Create Custom Query for WordPress

WordPress has a default query which fetches posts and display it in descending manner. If you are working on any WordPress customisation, you would come across a requirement to fetch WordPress posts in customised manner such as Fetching last 10 posts, Fetching post having specific category or tag.

Fortunately, we dont have to write MySQL level queries to get required data (and that what makes WordPress special), we can call a WP_Query function by passing required fields as input, we can get required data. This logic has two parts.

  1. Query : The query will select WordPress posts from the MySQL database based on our instructions.
  2. Loop : It will output the post information on the page. Each instance of output array will have attributes such as post thumbnail, title, date, and author etc.

Here is simple structure to help you understand custom WP_Query

// The Query
$the_query = new WP_Query( $args );

// The Loop
if ( $the_query->have_posts() ) {
    echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
    /* Restore original Post Data */
    wp_reset_postdata();
} else {
    // no posts found
}

 

You can customized the query as per your requirement.

<?php

// Creating array
$args = array( 
'posts_per_page' => 15, 
'orderby' => 'date', 
'order' ='ASC'
);
// Initiate the custom query
$custom_query = new WP_Query( $args );

?>

By Default, it will search for posts, if you want to search for specific custom post type, you can simply add a parameter in array

<?php

// Creating array
$args = array( 
'post_type' => 'vehicle',
'posts_per_page' => 15, 
'orderby' => 'date', 
'order' ='ASC'
);
// Initiate the custom query
$custom_query = new WP_Query( $args );

?>

How to restrict plugin access to multisite

WordPress multi-site is a great tool, it helps in creating network blogs with much easy. However, you need to be careful when allowing user full control. WordPress plugins can be misused by sub sites.

If you want to disable plugins, you can disable is very easily. Login using super admin and go to

Network Admin –> Settings –> Network Settings

Scroll all the way to down and un-check the plugin check box

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 show breadcrumb navigation in WordPress

Breadcrumb generally do not get their due importance in many themes. Once of the reason being most of the users misuse categories and tags. Unless you have clear understanding of how to use Categories and Tags, you wont be able to understand importance of Breadcrumb.

Breadcrumb helps yours users to navigate across your websites in most intuitive way.  Here is an example. This site has list of tourist places and Breadcrumb makes this very intuitive

Please follow below mention steps

Step#1 Enable Breadcrumbs using Yoast SEO plugin

Go to SEO–>Search Appearance

Please note, if you are using custom post type, you will get an option to choose which taxonomy needs to be used as Breadcrumb

Setp#2 Add the code

You can add below code where you need Breadcrumbs needs to be displayed. It varies across different themes. For most of the themes, if you copy this at the end of header.php file, it should work.

Alternatively, you can copy below code just above single.php just above the line which displays post title.

 <?php if ( function_exists('yoast_breadcrumb') ) 
 {yoast_breadcrumb('<p id="breadcrumbs">','</p>');} ?>

If breadcrumbs are still not visible, please let me know.

How to redirect HTTP to HTTPS in Nginx

When I had installed Letsencrypt SSL, it was working fine. Some of the sites were automatically getting redirected from http to https however some some sites, it was not happening. Here is the server block code. Simply copy paste this before your existing server block and it will redirect http to https.


server {
        listen 80 default_server;
        listen [::]:80 default_server;
        server_name _;
        return 301 https://$host$request_uri;
}

Please do let me know if this addressed your requirement.

How to Add a Favicon to Your WordPress Blog

Favicon gives website a professional look. Most of the reputed websites use facicon and its displayed in browser as below:

Another reason for adding favicon is that it makes your website more trsutful. Adding favicon in WordPress is very easy.

Step#1 Decide the Favicon

Favicon can be logo, character or any image that would be your websites identity. Mostly favicons are websites logo.

Step#2 Upload favicon to WordPress website

Go to Appearance–> Customise–>Site Identity

Here, click on Change image, select whichever image you have finalised in Step#1 and click on Publish.

Thats all, you websites favicon/identity is updated

Troubleshooting:

Even after publishing favicon was not getting updated for me.I opened website in another tab, still issue persisted. To refresh favicon follow following steps

  1. Hover over tab
  2. Right Click
  3. Select reload
  4. Your favicon should now be refreshed

 

Documentation for DW Question & Answer Plugin

This is quick notes for DW Questions & Answer Plugin

Short codes:

Ask Question page : [dwqa-submit-question-form]

List of Questions:  [dwqa-list-questions]

using shortcode in php code:

<?php echo do_shortcode(‘[dwqa-popular-questions number=”3″ title=””]’); ?>

 

Code:

List of categories

<ul><?php wp_list_categories('taxonomy=dwqa-question_category&hide_empty=0&show_count=1&orderby=id&title_li=');?></ul>

 

Custome Post type is

dwqa-question

dwqa-answer

 

How to move WordPress site to new domain without losing SEO

Sometimes after starting a website or a blog, user might recognises that, he needs a different domain name or he would like to move to different domain suffix (he might want to move from *.net to *.com or he might would like to move to country specific domain suffix like *.in for India, *.de for Germany ,*.fr for France etc). Whatever might be the reason, following steps needs to be followed for effective movement without losing SEO

Before you start further, current website is the live example of domain migration. I had started this website with domain name as www.techtrekking.net, I was owning domain www.techtrekking.com but I was planning to use it for one of my other requirement. After realising that its not a good idea to use same domain name for two different ideas, I decided to move from .net to .com domain.

To test how this is working, please click following .net links and please see yourself, what is the actual site its opening

You can test this for any other url on this website and validate its functioning.

Before you start

You have two options for doing this change 1. Do the change on the live site 2. Do the changes on backup.

I suggest to use the second approach. Here, you don’t touch existing WordPress folder, you create a copy of current WordPress installation with new domain and simply change nginx config of old domain.

Step#1 Take Backup

This is the most important as you dont know what can go wrong during the migration. If something goes wrong, you can simply override the changes with the backups that you have. You need to take backup of three things

  • MySQL Database backup.
mysqldump -u [username] -p [databaseName] > [databaseName].sql
  • Folder which has your code (WordPress folder, including themes and plugins

Connect to your server using filezilla and copy folder as well as  MySQL dump to your location machine.

  • Back up NGINX config file

NGINX config file for any domains are located @ /etc/nginx/sites-available on a Ubuntu server

Step#2 Configure new domain on server

You need to make sure you have added A and CNAME records correctly. On your server as well as your domain registrar. This is exactly same as that of your earlier domain nothing different.

Once done, please create a nginx config file as explained in this post. Please refer to “Configure nginx” of this post.

This step is nothing new, it’s same that you would have followed while setting up your earlier domain which you need to be replaced with new domain.

Step#3 Changing the domain name

Go to Settings–>General and change the URLs from existing domain name to desired domain name.

Once you save this, you might get automatically logged off and you will have to login again. This will login using new domain

Step#4 Update internal and hard-coded links

You might have internal reference to your sites between different posts. Also, some links might be hard-coded in navigation bar. You need to get these changed. Changing this manually is easy if you have very few posts but if you have 50+ posts on your blog, doing this manually is not a good choice from efficiency and effectiveness point of view. You have following options to do this.

  1. Use the Velvet Blues Update URLs plugin if you can access your WP Admin Dashboard.
  2. Use the Better Search Replace plugin if you can access your WP Admin Dashboard.
  3. Use WP-CLI’s search-replace if your hosting provider (or you) have installed WP-CLI.
  4. Use the Search and Replace for WordPress Databases Script to safely change all instances on your old domain or path to your new one. (** only use this option if you are comfortable with database administration ** )

I personally used Velvet Blues Update URLs and it was effective.

Step#5 Adding 301 redirect.

Now you have moved to new blog, your internal links are taken care of but what about external links ? Someone might have hard-coded you link ? For example, one of my post was mentioned in a GitHub issue as a solution. This issue is already closed, I can not ping everyone to change the user reference. Then how to handle it ?

Best solution is using 301 redirect in your old domains server. I am using NGINX and this can be achieved using below

server {

    server_name techtrekking.net www.techtrekking.net;
    return 301 $scheme://techtrekking.com$request_uri;
}

Note: You need to continue owning old domain to ensure redirect is happening

Step#6 Updating Google and Bing webmaster

Since, Google and Bing will crawl your websites based on details you have provided in webmaster tools, updating your website with correct domain is very crucial.

Most important part is you update you sitemaps.

Step#6 Update Google Analytics (Optional, needed only if you are using Google Analytics)

Once this is done, you will continue to get new visitors using SEO as well as you will not lose your existing visitors due to