我有一个自定义的帖子类型,它有一堆帖子,格式都像
Artist - Song Title
例如
The Smashing Pumpkins - Quiet
我试图将"艺术家"放在变量$Artist中,将"歌曲标题"放在可变的$Song 中
$artistsong = get_the_title();
$songeach = explode("-", $artistsong);
$artist = $songeach[0];
$song = $songeach[1];
但这并不奏效。Echo ing$艺术家获得完整标题
The Smashing Pumpkins - Quiet
并且回显$song不会输出任何
如果我只是从纯文本开始,但不使用"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()之外,是否还有其他方法可以将完整的标题最初放入变量中,这似乎对我不起作用,或者我缺少了其他东西?
将此代码添加到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;
因为apply_filters
函数将连字符从-
=>–
更改。
这是因为短划线符号。
试试$songeach = explode("P", $artistsong);
,你就会明白我的意思。你可以在歌手和歌曲标题之间尝试一个不同的角色——尽管可能并不理想。