I'm trying to get a post offset to work on category and tag archives with a couple of category exclusions.
I have 3 functions. The first creats a custom loop which is inserted via shortcode and contains 3 posts, and the other two functions offset the main query by 3 and fix the pagination as per this codex article
It seems to work where it should, except it's also offsetting posts in the backend admin area for all post types and I can't work out how to stop that happening.
For clarity, posts should be offset by 3 on category and tag archives only, excluding the categories added to the array.
function archive_loop_shortcode() {
$current_archive = get_queried_object();
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 3,
'tax_query' => array(
array(
'taxonomy' => $current_archive->taxonomy,
'field' => 'term_id',
'terms' => $current_archive->term_id,
),
),
);
$archive_query = null;
$archive_query = new WP_query($args);
echo '<div class="kb-custom-archive-loop"><div class="kb-custom-archive-loop-inner">';
if($archive_query->have_posts()):
while($archive_query->have_posts()) : $archive_query->the_post();
$custom = get_post_custom( get_the_ID() );
echo '<article>';
echo '<figure><a href="' . get_permalink() . '"><div>' . get_the_post_thumbnail() . '</div></a></figure>';
echo '<a href="' . get_permalink() . '"><h2>' . get_the_title() . '</h2></a>';
echo '</article>';
endwhile;
wp_reset_postdata();
else :
_e( 'Sorry, no posts matched your criteria.' );
endif;
echo "</div></div>";
}
add_shortcode( 'archive_loop', 'archive_loop_shortcode' );
add_action('pre_get_posts', 'myprefix_query_offset', 1 );
function myprefix_query_offset(&$query) {
if ( ! is_admin() && ! is_home() && ! is_search() && ! is_author() && ! $query->is_main_query() ) {
if ( ! is_category(array('28770','28688')) || is_tag() ) {
return;
}
}
$offset = 3;
$ppp = get_option('posts_per_page');
if ( $query->is_paged ) {
$page_offset = $offset + ( ($query->query_vars['paged']-1) * $ppp );
$query->set('offset', $page_offset );
}
else {
$query->set('offset',$offset);
}
}
add_filter('found_posts', 'myprefix_adjust_offset_pagination', 1, 2 );
function myprefix_adjust_offset_pagination($found_posts, $query) {
$offset = 3;
if ( ! is_admin() && ! is_home() && ! is_search() && ! is_author() && ! $query->is_main_query() ) {
if ( ! is_category(array('28770','28688')) || is_tag() ) {
return $found_posts - $offset;
}
}
return $found_posts;
}