Reputation: 1151
So I kind of have this working however it's outputting wrong.
E.G. I have 3 pages which are being queried through a loop.
I'd like them to look like this:
Chesty
Coughs (with a br after the first word)
This is what I've managed so far and it seems to work:
$tit = get_the_title();
$parts = preg_split('/\s*,\s*/', $tit);
foreach($parts as $part) {
preg_match_all('/\S+\S+/', $part, $names);
foreach($names[0] as $name) {
$separate.= "$name<br/>";
}
}
HOWEVER after each post the last title seems to get added onto the one before
E.G. < - - - firstpost - - - >
Chesty
Coughs
< - - - next post - - - >
Chesty
Coughs
Chocolate
Buttons
< - - - next post - - - >
Chesty
Coughs
Chocolate
Buttons
Dairy
Milk
This is my entire loop:
$args = array(
'post_type' => 'page',
'post_status' => 'publish',
'meta_query' => array(
array(
'key' => '_wp_page_template',
'value' => 'template-name.php' // template name as stored in the dB
)
)
);
$my_query = new WP_Query($args);
// The Loop
if ( $my_query->have_posts() ) {
while ( $my_query->have_posts() ) {
$my_query->the_post();
$tit = get_the_title();
$parts = preg_split('/\s*,\s*/', $tit);
foreach($parts as $part) {
preg_match_all('/\S+\S+/', $part, $names);
foreach($names[0] as $name) {
$separate.= "$name<br/>";
}
}
echo '<h3>'.$separate.'</h3>';
}
}
wp_reset_postdata();
How would I fix it so it outputs correctly?
Upvotes: 0
Views: 1504
Reputation: 27102
Way too complicated. You're seeing titles concatenated because you're telling it to with .=
. There's no need to do it that way. Instead, just replace the ' '
(space) string with a '\n'
newline or '<br>'
.
if ( $my_query->have_posts() ) {
while ( $my_query->have_posts() ) {
$my_query->the_post();
$title = get_the_title();
echo '<h3>' . str_replace(" ", "<br>", $title) . '</h3>';
}
}
wp_reset_postdata();
Upvotes: 3