最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

custom post types - Why does not this wp_redirect work in is_single()?

programmeradmin2浏览0评论

I have a custom post type (portfolio) and I have to redirect a certain page (of this custom post type) to another page.

when I look at my custom post type page:

So I wrote the code as follow to redirect the above 'portfolio' page :

if (is_singular('2024')) {
   wp_redirect('/../rugby/');
}

but when I visit to the page (ID=2024) in front end it does not redirect to the page /../rugby/ why is that?

  • 2024 - is a custom post type page's ID
  • /../rugby/ - is a default 'page' type not a 'post' type in wp.

I have a custom post type (portfolio) and I have to redirect a certain page (of this custom post type) to another page.

when I look at my custom post type page:

So I wrote the code as follow to redirect the above 'portfolio' page :

if (is_singular('2024')) {
   wp_redirect('http://mysitedomain/../rugby/');
}

but when I visit to the page (ID=2024) in front end it does not redirect to the page http://mysitedomain/../rugby/ why is that?

  • 2024 - is a custom post type page's ID
  • http://mysitedomain/../rugby/ - is a default 'page' type not a 'post' type in wp.
Share Improve this question asked Mar 30, 2016 at 11:05 Riffaz StarrRiffaz Starr 7964 gold badges20 silver badges41 bronze badges 2
  • you should add exit after. – RRikesh Commented Mar 30, 2016 at 13:42
  • exit isn't necessary after redirection! – Sumit Commented Mar 30, 2016 at 15:31
Add a comment  | 

1 Answer 1

Reset to default 5

is_singular() only accept post_type, use is_single('2024') for specific post.

if (is_single(2024)) {
     wp_redirect('http://mysitedomain/../rugby/');
     exit();
}

Update:

Also wp_redirect() does not work after headers are sent. Please make sure you are redirecting before headers. So you can hook this function on template_redirect and put this in functions.php

function redirect_custom_page() {
   if (is_single('2024')) {
        wp_redirect('http://mysitedomain/../rugby/');
        exit();
   }
}
add_action('template_redirect', 'redirect_custom_page');
发布评论

评论列表(0)

  1. 暂无评论