duankao4489 2014-12-10 15:30
浏览 30
已采纳

Wordpress - 标题中第一个单词后的换行符

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.

  1. Chesty Coughs
  2. Chocolate Buttons
  3. Dairy Milk

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?

  • 写回答

1条回答 默认 最新

  • douyimiao1993 2014-12-10 15:34
    关注

    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 ' ' 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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭