Use this snippet together with the Disclaimify plugin to display your affiliate disclosures only with those blog posts or pages that actually have affiliate links in them.
Add this either to the functions.php file of your current theme, or as a new code snippet using a plugin like Code Snippets.
function update_has_go_link_meta( $post_id, $post, $update ) {
// Don't do anything if this is an autosave or a revision
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if ( wp_is_post_revision( $post_id ) ) return;
// Only target 'post' post type
if ( 'post' !== $post->post_type ) return;
// Use regex to check for an <a> tag with /go/ in the href
$has_go_link = preg_match( '/<a\s[^>]*href=[\'"][^\'"]*\/go\/[^\'"]*[\'"]/i', $post->post_content ) ? 1 : 0;
// Save the result in a custom field
update_post_meta( $post_id, '_has_go_link', $has_go_link );
}
add_action( 'save_post', 'update_has_go_link_meta', 10, 3 );
function append_shortcode_if_go_link( $content ) {
if ( is_single() && in_the_loop() && is_main_query() ) {
global $post;
// Retrieve the stored flag (defaults to 0 if not set)
$has_go_link = get_post_meta( $post->ID, '_has_go_link', true );
if ( $has_go_link ) {
// Append the output of the shortcode
// REPLACE WITH THE ID OF THE DISCLOSURE YOU WANT TO USE
$content .= do_shortcode("[disclaimify id='999']");
// Alternatively, use this line and add a custom paragraph
// instead of using the Disclaimify plugin:
//$content .= '<p>Just a test paragraph</p>';
}
}
return $content;
}
add_filter( 'the_content', 'append_shortcode_if_go_link' );