how to bulk add one line in the first paragraph of all posts

admin2025-06-06  7

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.

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.

Share Improve this question edited Nov 18, 2018 at 18:35 Krzysiek Dróżdż 25.6k9 gold badges53 silver badges74 bronze badges asked Nov 16, 2018 at 19:11 Link NetworkLink Network 31 bronze badge 0
Add a comment  | 

2 Answers 2

Reset to default 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.

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;
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749169959a316950.html

最新回复(0)