2016-07-22 71 views
2

我有了一堆帖子全部被格式化为像这样设置WordPress的标题为两个独立的变量

Artist - Song Title 

例如自定义后类型

The Smashing Pumpkins - Quiet 

我试图把“艺术家”在变量$艺术家和'歌曲标题'中的一个变量$歌曲

$artistsong = get_the_title(); 
$songeach = explode("-", $artistsong); 
$artist = $songeach[0]; 
$song = $songeach[1]; 

但是这不起作用。回声荷兰国际集团$艺术家得到完整的标题

The Smashing Pumpkins - Quiet 

和呼应$歌无法正常输出

这个作品,如果我只是从纯文本出发,但与“get_the_title()”

$song = "The Smashing Pumpkins - Quiet"; 
$songeach = explode("-", $song); 
$artist = trim($songeach[0]); 
$song = trim($songeach[1]); 
echo $artist; 
     //echos 'The Smashing Pumpkins' 
echo $song; 
     //echos 'Quiet' 

有没有另一种方法可以将完整的标题放入一个最初的变量,而不是get_the_title(),它似乎不适合我,或者我错过了其他的东西?

+0

你确定这是一个“破折号”字符,而不是像“–”或“—”这样的东西吗? –

+0

你插入这个代码的地方? –

+0

Marc B - 我echo'd get_the_title()并复制了我的代码编辑器中提供的短划线。 – bbruman

回答

1

将此代码添加到您的functions.php

function get_the_title_keep_hyphen($post = 0) { 
    $post = get_post($post); 

    $title = isset($post->post_title) ? $post->post_title : ''; 
    $id = isset($post->ID) ? $post->ID : 0; 

    if (! is_admin()) { 
     if (! empty($post->post_password)) { 

      /** 
      * Filter the text prepended to the post title for protected posts. 
      * 
      * The filter is only applied on the front end. 
      * 
      * @since 2.8.0 
      * 
      * @param string $prepend Text displayed before the post title. 
      *       Default 'Protected: %s'. 
      * @param WP_Post $post Current post object. 
      */ 
      $protected_title_format = apply_filters('protected_title_format', __('Protected: %s'), $post); 
      $title = sprintf($protected_title_format, $title); 
     } elseif (isset($post->post_status) && 'private' == $post->post_status) { 

      /** 
      * Filter the text prepended to the post title of private posts. 
      * 
      * The filter is only applied on the front end. 
      * 
      * @since 2.8.0 
      * 
      * @param string $prepend Text displayed before the post title. 
      *       Default 'Private: %s'. 
      * @param WP_Post $post Current post object. 
      */ 
      $private_title_format = apply_filters('private_title_format', __('Private: %s'), $post); 
      $title = sprintf($private_title_format, $title); 
     } 
    } 

    /** 
    * Filter the post title. 
    * 
    * @since 0.71 
    * 
    * @param string $title The post title. 
    * @param int $id The post ID. 
    */ 
    return $title; 
} 

而且在使用该代码的single.php

$artistsong = get_the_title_keep_hyphen(); 
$songeach = explode(" - ", $artistsong); 
$artist = $songeach[0]; 
$song = $songeach[1]; 

看到最后一行

我从return apply_filters('the_title', $title, $id);改变return $title;

的Bec使用apply_filters函数从- =>更改连字符。

0

这是因为短划线的符号。

尝试$songeach = explode("P", $artistsong);你会明白我的意思。您可以在艺术家和歌曲标题之间尝试不同的角色 - 尽管可能并不理想。