Family Encyclopedia >> Electronics

How to Automatically Add a 'Sponsored' Prefix or Suffix to WordPress Post Titles

As experienced WordPress developers, we've helped countless bloggers clearly label sponsored content. Recently, a user asked how to automatically prepend "Sponsored" to post titles. Follow this proven step-by-step guide to implement it using custom fields.

How to Automatically Add a  Sponsored  Prefix or Suffix to WordPress Post Titles

Add Sponsored Prefix Using Custom Fields

Custom fields let you attach metadata to posts. We'll use one called 'sponsored' to flag content.

Create a new post or edit an existing one. Scroll to the Custom Fields metabox in the editor. If it's not visible, click Screen Options in the top-right corner and check the Custom Fields box.

How to Automatically Add a  Sponsored  Prefix or Suffix to WordPress Post Titles

In the Custom Fields metabox, add sponsored as the Name and true as the Value. Save the post. Next time, select it from the dropdown for quick reuse.

How to Automatically Add a  Sponsored  Prefix or Suffix to WordPress Post Titles

Now, add this code snippet to your theme's functions.php file or a site-specific plugin:

add_filter( 'the_title', 'wpb_sponsored_prefix' );
function wpb_sponsored_prefix( $title ) {
    global $post;
    $sponsored_text = '<span class="sponsored-prefix">Sponsored: </span>';
    $sponsored = get_post_meta( $post->ID, 'sponsored', true );
    if ( $sponsored === 'true' && in_the_loop() ) {
        return $sponsored_text . $title;
    }
    return $title;
}

Visit the post—you'll see "Sponsored: " prefixed to the title. The text is wrapped in a CSS class for styling. Add this to your child theme's stylesheet:

.sponsored-prefix {
    background: #eeffee;
    font-size: small;
    text-transform: uppercase;
    padding: 5px;
}

Customize the CSS as needed for your site's look.

Add Sponsored Suffix to Post Titles

For a suffix instead, use this modified snippet:

add_filter( 'the_title', 'wpb_sponsored_suffix' );
function wpb_sponsored_suffix( $title ) {
    global $post;
    $sponsored_text = ' <span class="sponsored-suffix">Sponsored</span>';
    $sponsored = get_post_meta( $post->ID, 'sponsored', true );
    if ( $sponsored === 'true' && in_the_loop() ) {
        return $title . $sponsored_text;
    }
    return $title;
}

We just swapped the order and added a space before the suffix.

That's it! This reliable method ensures compliance and transparency for sponsored posts. If you found this helpful, subscribe to our WordPress YouTube channel for video tutorials. Follow us on Twitter and Google+.