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.
2 Answers
Reset to default 1I'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;
}