Can any body help Me?
I want to create an in process condition to display a single post on wordpress. for example, I want to first check the post slug, if there is a "news-" character in the first of slug (Ex: domain[dot]com/news-anything-another-text), then single.php will output what I want to display. but if there is no "news-" character in the first of slug, then single.php displays published posts which corresponds to the slug. However, if there is no "news-" character in the slug, and there are no public posts such as the slug. Then the system will do something to the error page 404
CodePudding user response:
If you want to display custom content for a not found post if the slug starts with "news", you need to redirect the user to a different page and show the content there.
Add the below code in the functions.php Make sure you have created that custom page before doing this redirect
function rf_custom_redirect() {
$page_slug = $_SERVER['REQUEST_URI'];
$link_array = explode('/',$page_slug);
$page = end($link_array);
$firstword = strtok($page, "-");
if( is_404() && $firstword == "news"){
//Code you want to execute if the first word is news
wp_redirect( home_url( '/custom-page/' ) );
exit();
}
else
{
//Code you want to execute if the first word is not news
}
}
add_action( 'template_redirect', 'rf_custom_redirect' );
Below code is to display specific content in single.php if blog post slug starts with news.
First, You need to get the POST SLUG/URL in the single.php file(Single Blog Post template). For that, use the below code.
global $post;
$page_slug = $post->post_name;
There is a string function (strtok) in PHP which can be used to split a string into smaller strings (tokens) based on separator. In our case, the separator would be hypen(-).
We can get the first word of the page slug using the code below.
$firstword = strtok($page_slug, "-");
Then you just check if the $firstword is "news" using a simple IF condition.
if($firstword == "news")
{
//Code you want to execute if the first word is news
}
else
{
//Code you want to execute if the first word is not news
}