Last active
May 21, 2018 07:36
-
-
Save dbranes/bf5c38fd5e82153446ac to your computer and use it in GitHub Desktop.
WordPress: Inject custom post type posts, that are attached to a given term of a custom taxonomy, into the main loop and the feed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Inject posts of the custom post type 'usp_post', that are attached to the 'featured' term of the | |
* 'firstpage' taxonomy, into the main loop and the feed. | |
* @see http://www.wpquestions.com/question/showChronoLoggedIn/id/10370 | |
*/ | |
add_filter( 'pre_get_posts', 'wpq_pre_get_posts', 99 ); | |
function wpq_pre_get_posts( $query ) | |
{ | |
if ( ( is_front_page() && $query->is_main_query() ) || is_feed() ) | |
{ | |
$query->set( 'post_type', array( 'post' ) ); | |
add_filter( 'posts_where', 'wpq_posts_where', PHP_INT_MAX ); | |
} | |
} | |
function wpq_posts_where( $where ) | |
{ | |
global $wpdb; | |
remove_filter( current_filter(), __FUNCTION__, PHP_INT_MAX ); | |
// Modify this to your needs for the injected posts: | |
$taxonomy = 'firstpage'; // <-- This should be the taxonomy. | |
$term_slug = 'featured'; // <-- This should be the term slug. | |
$cpt = 'usp_post'; // <-- This should be the custom post type. | |
// Get the term info for the term_taxonomy_id: | |
$term = get_term_by( 'slug', $term_slug, $taxonomy ); | |
// Modify the SQL query: | |
if( ! is_wp_error( $term ) ) | |
{ | |
$where .= " OR {$wpdb->posts}.ID IN ( | |
SELECT object_id FROM {$wpdb->term_relationships} WHERE term_taxonomy_id IN ( {$term->term_taxonomy_id} ) ) | |
AND {$wpdb->posts}.post_status = 'publish' | |
AND {$wpdb->posts}.post_type = '{$cpt}' "; | |
} | |
return $where; | |
} | |
/** | |
* Some other modifications that you might have: | |
*/ | |
function limit_posts_per_home_page( $query ) | |
{ | |
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; | |
$first_page_limit = 11; | |
$limit = get_option('posts_per_page'); | |
if ( is_front_page() ) | |
{ | |
if ( $paged == 1 ) | |
{ | |
$limit = $first_page_limit; | |
} | |
else | |
{ | |
$offset = $first_page_limit + ( ( $paged - 2 ) * $limit ); | |
set_query_var( 'offset', $offset ); | |
} | |
} | |
set_query_var('posts_per_archive_page', $limit); | |
set_query_var('posts_per_page', $limit); | |
} | |
add_filter('pre_get_posts', 'limit_posts_per_home_page'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you should do
add_action()
if the function is not returning any value