所以我想得到新发布文章的永久标题,例如 "http:/myblog.comhealthy-life.php",我需要healthy-life.php。
这是我的代码,但它让我 http:/myblog.comhealthy-life.php
function get_laterst_post_url() {
global $wpdb;
$query = "SELECT ID FROM {$wpdb->prefix}posts WHERE post_type='post' AND post_status='publish' ORDER BY post_date DESC LIMIT 1;";
$result = $wpdb->get_results($query);
if(is_object($result[0])) {
return get_permalink($result[0]->ID);
} else {
return '';
};
}
你可以添加。
$url = get_bloginfo('wpurl') . "/";
$permalink_title = str_replace($url, "", get_permalink($result[0]->ID));
return $permalink_title;
但最好使用wordpress的功能来获取链接。比如说
function get_laterst_post_url() {
$args = array(
'numberposts' => 1,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'suppress_filters' => true );
$recent_posts = wp_get_recent_posts();
$url = get_bloginfo('wpurl') . "/";
$permalink_title = str_replace($url, "", get_permalink($recent_posts[0]["ID"]));
return $permalink_title;
}
使用 PHP的explode() 来分割斜线处,并抓取数组的最后一块。
// get the full URL, removing a trailing slash if it has one
$permalink = rtrim(get_permalink($result[0]->ID), "/");
// break that full URL into an array of the strings between each slash
$segments = explode("/", $permalink);
// get the last item in that array of segments
return array_pop($segments);
感谢@Leander对尾部斜杠的调整,也感谢他在9年的时间里对我的例子进行评论。