如何修复PHP函数以将广告代码放入附件页面内容?

How to fix a PHP function to place the ad code into attachment page content?


This code shows the ad on the attachment page :

<?php function get_ad () {
    return ' ad code ';
}

add_shortcode('ads', 'get_ad'); 
?>

This redirects the attachment page to the parent page :

<?php 
wp_redirect(get_permalink($post->post_parent), 301);
exit; 
?>

I want to add an if loop in the code above. I added this code to the image.php page. If the "[ads]" shortcode is included in an attachment content, I want to see an ad on the attachment page. if this [ads] code does not exist then I want to redirect the attachment page to the parent post page. I mean, I want to combine these two codes.

I want to do the following:

1) if (if an ad code has been added ...)

2 ) show ad

3) if not show

4) redirect to parent page

Thank You