2

I use the following code to get the Next /Previous link in the same category

In localhost, it worked good but in my Cpanel host doesn't good working Following code: First, get current id post and category and then reserve post by date

In WordPress, I posted articles regularly by time.

I have 20 posts and I want to display next / prev button in all 20 posts but only displays in 4 posts

    <?php 
    $post_id = $posts->ID; // current post id
    $cat = get_the_category(); 
    $current_cat_id = $cat[0]->cat_ID; // current category id

    $args = array('category'=>$current_cat_id,'orderby'=>'post_date','order'=> 'DESC');
    $posts = get_posts($args);
    // get ids of posts retrieved from get_posts
    $ids = array();
    foreach ($posts as $thepost) {
        $ids[] = $thepost->ID;
    }
    // get and echo previous and next post in the same category
    $thisindex = array_search($post->ID, $ids);
    $previd = $ids[$thisindex-1];
    $nextid = $ids[$thisindex+1];

    if (!empty($previd)){
    ?>
    <a class="ls-right w3-btn prev"el="prev" href="<?php echo get_permalink($previd) ?>">PreLink</a>
    <?php
    }
    if (!empty($nextid)){
    ?>
    <a  class="ls-left w3-btn " href="<?php echo get_permalink($nextid) ?>">NextLink</a>
    <?php
    }
1

I use the following code to Displays Next/Previous link in same posts category and work correctly for me.

<?php


 get_template_part( 'content', get_post_format() );

 // Previous/next post navigation.
 previous_post_link('%link', 'Before', true );
 next_post_link( '%link', 'Next', true );

 ?>

And For CSS Styling the "%link" Element I use this code in my functions.php file.

  /////Next/Prev post style

  add_filter('next_post_link', 'next_post_link_attributes');
  add_filter('previous_post_link', 'previous_post_link_attributes');

   function next_post_link_attributes($output) {/// Styling next link

     $injection = 'class="ls-left w3-btn"';
     return str_replace('<a href=', '<a '.$injection.' href=', $output);

    }

  function previous_post_link_attributes($output) {/// Styling previous link

   $injection = 'class="ls-right w3-btn prev"';
   return str_replace('<a href=', '<a '.$injection.' href=', $output);

   }

Top code: I use 2 different functions "previous_post_link_attributes" and "next_post_link_attributes" Because I want to add different CSS style for nex/pre links

If you want to add the same style to next/pre links you can use one method:

add_filter('next_post_link', 'post_link_attributes');
add_filter('previous_post_link', 'post_link_attributes');

function post_link_attributes($output) {
$injection = 'class="my-class"';
return str_replace('<a href=', '<a '.$injection.' href=', $output);
}

For more about next / pre link --> wpcodex ,masternsblog ,wp-stack

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.