QNimate

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

WordPress Add Custom Post Type to Archive

Here is the code to add custom post type to archive pages

<?php

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

    if(is_tag() || is_category())
    {
        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_archive");

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, search, archive 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
WordPress Add Custom Post Type to Search ResultFacebook Style Infinite Scroll
Comments: 1
  1. victor
    5 years ago

    waooo.. this blog help me to solve my issue…thank you

    ReplyCancel

Leave a Reply to victor 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.

8 years ago 1 Comment 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 Posts Index Page
  • WordPress Set HTML Editor as Default
  • WordPress Set Visual Editor as Default
  • WordPress Custom Meta Boxes Tutorial
Our Sponsor
My Books

2014 - 2015 © QNimate
All tutorials MIT license