0

Since Wordpress sticky posts feature allow the post checked as sticky in post publish panel to be placed at the top of the front page of posts. I was also intended to style the sticky post differently than normal ones within the loop by customizing The Loop default coding as following:

        <?php if (have_posts()) : ?>
        <?php $post = $posts[0]; $c=0;?>
        <?php while (have_posts()) : the_post(); $do_not_duplicate = $post->ID; ?>

        <?php $c++;
        if( is_home() && !$paged && $c == 1) :?>
        <?php get_template_part( 'includes/sticky-post', 'page' ); ?>

        <?php else :?>
        <?php get_template_part( 'includes/loop-post', 'page' ); ?>

        <?php endif;?>

        <?php endwhile; ?>
        <?php endif; ?>

Where template parts includes/sticky-post and includes/loop-post have post content layout for sticky and normal ones respectively, I still having sticky post twice. Once at the top as required with assigned layout and the other at its normal order of publish date within normal posts which I seeking help to get rid of this issue of duplication.

Any help is much appreciated.

2

You simply need the is_sticky() conditional check and then act on that. You would probably still need the is_home() and !is_paged() conditional check to only target stikies on the first page of the home page

if ( have_posts() ) :
    while ( have_posts() ) :
        the_post();

        if (    is_sticky()
             && is_home()
             && !is_paged()
        ) {
            // Do what you need to do for stickies
        } elseif ( !is_sticky() ) {
            // Do something else for non-stickies  
        }
    endwhile;
endif;
  • 1
    Your code worked except you may missed replacing else with elseif (!is_sticky()) to exclude duplicated sticky post from non-stickies layout – user86113 May 22 '16 at 22:41
1

You'll have to move the part that says $do_not_duplicate = $post->ID; to the conditional statement that leads to the first get_template_part(). Now you have stored the ID of that sticky post.

if( is_home() && !$paged && $c == 1) {
    $do_not_duplicate = $post->ID;
    get_template_part( 'includes/sticky-post', 'page' ); 
    }

Next, in the else part you have to add another condition to make sure you do nothing if the sticky post appears again (which you know if the ID of the current post is the same as the value you stored earlier):

if ($do_not_duplicate != $post->ID) get_template_part( 'includes/loop-post', 'page' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy