0

I want to add a sentence at the beginning of all posts of content directly into the post_content WordPress database. How do I? Either through the function.php or the MySQL command.

0
1

I'd go for solution posted by @butlerblog - it's a lot easier to manage and change in the future and it's better WP practice.

But... If you're asking... Here are the ways you can do this:

1. WP way:

function prepend_content_to_posts() {
    $to_prepend = 'This will be prepended';

    $posts = get_posts( array( 'posts_per_page' => -1 ) );
    foreach ( $posts as $post ) {
        wp_update_post( array(
            'ID' => $post->ID,
            'post_content' => $to_prepend . $post->post_content
        ) );
    }
}

Then you'll have to call that function. Be careful not to call it twice - it will add your content twice in such case.

2. MySQL way:

UPDATE wp_posts
    SET post_content = CONCAT('<YOUR STRING TO PREPEND>', post_content) 
    WHERE post_type = 'post' AND post_status = 'publish'

Be careful to change table prefix according to your config.

2
  • Thank you for sharing your knowledge, I have tried it and managed to add the first paragraph through mysql. but through the function has not been successful because the syntax error appears, unexpected ';', expecting ')'. this knowledge might be useful to me in the future. for now it seems like your suggestion and @butlerblog are the current solution. thank you – Link Network Nov 19 '18 at 12:44
  • @LinkNetwork Ah, thanks for your notice. You're right, there was a typo in PHP code. I've corrected that and both solutions should work now :) – Krzysiek Dróżdż Nov 19 '18 at 12:46
3

Rather than insert it directly into the db, why don't you add it to the content when displayed using the_content filter? That way, you don't make any db changes you might want to undo later.

add_filter( 'the_content', 'my_extra_line' );
function my_extra_line( $content ) {

    if ( "post" == get_post_type() ) {
        // If the content is a post, add an extra line to the content.
        $content = "My extra line of content. " . $content;
    }

    return $content;
}
1
  • thank you for the answer, I just want to know as basic knowledge if later it is needed. if there is a way please tell how – Link Network Nov 18 '18 at 11:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.