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 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计