Different html / css for first 4 posts in one request in Wordpress

I am trying to change the HTML structure and CSS styles of the first 4 posts in my main WP_Query in archive.php

I am doing this simple thing where I checked a global variable $wp_query

.

if ( have_posts() ) :

  if( 4 > $wp_query->current_post ) :
    the_title();
  endif;

  while ( have_posts() ) : the_post();

    get_template_part( 'content', get_post_format() );

  endwhile;

  else :

  get_template_part( 'no-results', 'archive' );

endif;

      

This works great, the first 4 messages in the request are rendered in whatever HTML / CSS I apply to them before being called get_template_part()

.

The problem is when I go to the next page in the pagination, a different set of 4 posts is displayed. 4 new posts on the second page, paginated.

I do not want it. I want the same 4 messages that appear on the first page to continue to display when I navigate to the next or previous page. I need to give the first 4 posts a different HTML structure, not just CSS styles, and I need them to persist throughout the entire page.

I tried changing the main query with pre_get_posts

and with help offset

, but that gave me a lot of issues in the theme and admin panel which I solved against it.

How can I achieve this?

EDIT . My first attempt at this problem was to execute the second query and leave the main query intact, but then I would not be able to check post_count

in the first query to see if it is greater than 4, because I always only show 4 posts_per_page

, so I need to they were in one request because I am going to hide the first 4 posts on a category page with no more than 4 posts and only show them on a category page with more than 4 posts.

EDIT 2 To make it easier to understand if it gets too messy.

IF CATEGORY (QUERY) HAS MORE THAN 4 POSTS

    DISPLAY 4 POSTS WITH CUSTOM HTML/CSS

    THEN GET TEMPLATE PART AND DISPLAY THE REST OF THE POSTS WHILE EXCLUDING THE FIRST 4 POSTS BECAUSE DUPLICATES

ELSE

    DISPLAY DEFAULT TEMPLATE PART

      

+3


source to share


2 answers


Here's the loop I'm using to show the first four posts has wp_reset_postdata, which may be required to keep your fragmentation loop unaffected.



<?php $rp_query = new WP_Query( 'showposts=4' );
    if ( have_posts() ) : while ( $rp_query->have_posts() ) : $rp_query->the_post(); ?>
    <?php endwhile; ?>
    <?php wp_reset_postdata(); ?>
    <? endif; ?>

      

0


source


The solution is already built in and available as a plugin. Please try the Blog Designer PRO plugin - https://codecanyon.net/item/blog-designer-pro-for-wordpress/17069678?ref=miyanialkesh7



Regards, Alkesh

-1


source







All Articles