I have variable working in the loop of my homepage, but when I try to use that line $variable = $post->post_title; $variable = str_replace( ' - ', '<br />' ,$variable); echo $variable; in my sidebar with the same loop, the title disappears.

$recentPosts = new WP_Query();

 <?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>

 <?php $variable = $post->post_title; $variable =    str_replace( ' - ', '<br />' ,$variable); echo $variable; ?>

1 Answer 1


The $post object is not available outside the Loop, unless you globalize it before referencing it:

global $post;
$variable = $post->post_title;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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