我有一个自定义帖子类型,其中包含大量帖子,所有格式都是这样的
Artist - Song Title
例如
The Smashing Pumpkins - Quiet
我试图将'Artist'放在变量$ artist中,将'Song Title'放入变量$ song
$artistsong = get_the_title();
$songeach = explode("-", $artistsong);
$artist = $songeach[0];
$song = $songeach[1];
但这不起作用。 Echo-ing $ artist获得完整的标题
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()的变量中,这对我来说似乎没有用,或者我错过了其他的东西?
答案 0 :(得分: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;
因为apply_filters
函数会更改-
=>中的连字符–
。
答案 1 :(得分:0)
这是因为破折号。
试试$songeach = explode("P", $artistsong);
,你会明白我的意思。你可以在艺术家和歌曲名称之间尝试不同的角色 - 虽然可能不理想。