QNimate

  • CoursesVideos
  • WP PremiumPlugins
  • DemosLab
  • Home
  • QIdea
  • QTrack
Home Carbon Ads WordPress Add Custom Post Type to Posts Index Page

WordPress Add Custom Post Type to Posts Index Page

Here is the code to add custom post type to posts index page

<?php

//$q is the global query object. Its type is WP_Object.
function add_custom_posttype_to_posts_index($q)
{
    if(is_admin())
    {
        return;
    }

    if(is_home())
    {
        if($q->is_main_query())
        {
            //custom post type name
            $custom_post_type_name = "";

            $post_type = $q->query_vars["post_type"];

            if(is_array($post_type))
            {
                $post_type[] = $custom_post_type_name;
                $q->set("post_type", $post_type);    
            }
            else
            {
                $q->set("post_type", array("post", $custom_post_type_name));
            }
        }
    }
}

add_action("pre_get_posts", "add_custom_posttype_to_posts_index");

When a frontend request is made to WordPress it first resolves the URL to a resource ID. And then it maps the resource ID to resource type(i.e., post, page, custom post type, index page etc). Now it knows the resource id and type so it creates the global query object. Then it loads the Theme’s functions and plugins. Now finally it makes the actual database query and fetches the resource data.

pre_get_posts action is triggered after the global query variable object is created, but before the actual query is run.

Mar 14, 2015Narayan Prusty
Header Compression in HTTP/2WordPress Add Custom Post Type to Search Result

Leave a Reply Cancel reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

Narayan Prusty

I am a software engineer specialising in Blockchain, DevOps and Go/JavaScript. This is my personal blog where I write about things that I learn and feel interesting to share.

7 years ago WordPress
Share this
0
GooglePlus
0
Facebook
0
Twitter
0
Linkedin
Related Articles
  • WordPress Add Custom Post Type to Search Result
  • WordPress Add Custom Post Type to Archive
  • Change WordPress Default Avatar
  • WordPress Enqueue Script in a Specific Admin Settings Page
  • WordPress Set HTML Editor as Default
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license