To comply with FTC guidelines, I'm trying to get all posts with affiliate links to have a disclaimer right before the post. After looking at different options, the idea that made the most sense was to tag my posts with affiliate links such as "affiliate." Then I could use some code to give me the disclaimer I want.

So I came across some code to make a widget before post content.

/** Register Before Post Widget Area.*/
function wpsites_before_post_widget() {

     register_sidebar( array(
        'name' => 'Before Post Widget',
        'id' => 'before-post',
        'before_widget' => '<div>',
        'after_widget' => '</div>',
    ) );
}
add_action( 'widgets_init', 'wpsites_before_post_widget' );

function before_post_widget($content) {

if ( is_singular(array('post', 'page')) && is_active_sidebar( 'before-post' ) && is_main_query() ) { 
            dynamic_sidebar('before-post', array(
        'before' => '<div class="before-post">',
            'after' => '</div>',
    ) );

    return $content;

    }

}

add_filter( 'the_content', 'before_post_widget' );

This worked and gave me a "Before Post Widget." I added my disclaimer text and it showed up on all my posts. Now I just needed to make it only show up on the pages with the "affiliate" tag.

I have Jetpack installed, so I was able to set the Visibility of the widget to "Show if tag is affiliate." Makes sense to me and seemed easy enough.

The problem is that on any post without the tag, the post content is completely missing. Everything else remains (header, sidebar, sharing, etc.) - but all the content disappears.

I made sure to turn off all caching before messing with this just to make sure I wasn't screwing anything up and was doing my tests with a different browser that isn't logged into my site, but the problem is still there.

The other problem is that on my pages (non-post), the disclaimer text would just show up twice on the top above everything including the header.

I had to delete the code from my the functions.php to get everything back to normal.

I'm not too well-versed in PHP - does the code shown make sense or should some changes be made to it? Is there a better way to accomplish this using the affiliate tags on my posts?

Thanks for any help!

-- Jim

有帮助吗?

解决方案

Is there a better way to accomplish this using the affiliate tags on my posts?

Definitely I would go for an easier option, not relying on plugins like Jetpack.

Why don't you try the has_tag function? Something like this:

function tt_filter_the_content( $content ) {
    if (has_tag('affiliate'))
    $custom_content = 'YOUR MESSAGE';
    $custom_content .= $content;
    return $custom_content;
}
add_filter( 'the_content', 'tt_filter_the_content' );

This will filter your content and add your "YOUR MESSAGE" on all posts with the "affiliate" tag name.

Reference https://developer.wordpress.org/reference/functions/has_tag/

许可以下: CC-BY-SA归因
scroll top