I have covered adding content to the end of your posts before, such as social sharing icons, or a newsletter signup box and the principles for adding content to the beginning of a post are very similar: you just need to jiggle things around a bit.
In my hypothetical situation, we’re going to assume that you’re using Custom Meta Boxes to store information against the post, which will then be evaluated to determine whether to show the content at the beginning of the post or not.
Let’s assume that you’re checking whether the post is a sponsored post, by seeing whether the appropriate meta key has been set against the post.
So you’d start by checking for that meta key using the get_post_meta function, which looks something like this:
Then we can check for another meta key, to determine what kind of sponsored content it is, to tailor the message a little better. The following checks to see whether the content type is a giveaway:
If both conditions are met, we might want to add a statement at the top of the post that indicates that this is a sponsored giveaway. In this case, we set a new variable ($sponsored_content) and add our statement, and then attach the post content after it:
Note that the practice of adding something before the content lies in setting a custom variable equal to the content you want to add, and then adding the content after it, which is found in the line: $sponsored_content .= $content;
We could add another conditional to look for a different content type and apply a different message, for example:
Then if we assemble all of that into a function, and account for the possibility that these conditions aren’t true (by simply returning the content, otherwise the post will be blank) and run it through the the_content filter, we get a snippet that looks something like this. This should go in your functionality plugin:
If you don’t have to worry about conditionals, then it becomes even easier, as you can just apply the additional content across the board with something like this:
Bear in mind that the_content filter works on every post type, so if you don’t want to apply this to your pages or other custom post types, you will need to use another conditional tag (such as is_single) to limit which post types the snippet should apply to.