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");
//$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.
Leave a Reply