• orkhanahmadov

    (@orkhanahmadov)


    Hi,

    I’ve searched and tried different methods but didn’t find correct working solution.
    I have a website with permalink structure https://www.example.com/category-name/post-name/, what I need is redirect all https://www.example.com/category-name/ request to first, newest post under that category. Does not matter the category have only one or hundred post, I always need to redirect to newest post.
    Also is it possible to apply this not all category links, but only to specific category?

    Thank you in advance.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Guaven Labs

    (@elvinhaci)

    Hey Orkhan. Go to your functions.php and paste this code there:

    add_action('get_header','redirecttofirstpost');
    function redirecttofirstpost(){
    if (is_category()){
    $cur_cat_id = get_cat_id( single_cat_title("",false) );
    $args = array( 'numberposts' => 1, 'category' =>$cur_cat_id );
    $myposts = get_posts( $args );
    foreach ( $myposts as $post ) :
    $pid=$post->ID;
     endforeach;
    wp_redirect( home_url('/?p='.$pid) );
    exit;
    }
    }

    Guaven Labs

    (@elvinhaci)

    For spesific category

    add_action('get_header','redirecttofirstpost');
    function redirecttofirstpost(){
    if (is_category()){
    $cur_cat_id = get_cat_id( single_cat_title("",false) );
    if ($cur_cat_id==YOUR_SPESIFIC_CATEGORY_ID) {
    $args = array( 'numberposts' => 1, 'category' =>$cur_cat_id );
    $myposts = get_posts( $args );
    foreach ( $myposts as $post ) :
    $pid=$post->ID;
     endforeach;
    wp_redirect( home_url('/?p='.$pid) );
    exit;
      }
     }
    }

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Redirect category to first post’ is closed to new replies.