如何在静态页面中得到最后post的标题?
How to have the title of the last post in a static page?
我有一个 post 页面和一个不同的静态主页,以及其他常用页面,例如关于、赞助商。
我试图在所有页面的 header 中包含站点名称和最后一个 post 的标题。我尝试了不同的函数(the_title()、get_the_title())。它在 post 页面中运行良好,但对于所有剩余的页面,我得到页面的标题("About" 或 "Home" 或 "Sponsors")。
我知道到目前为止我使用的函数可能只在循环内工作,但想知道是否有某种全局方法可以让最后一个 post 的标题随处可用。
我必须:$posts_page = get_option( 'page_for_posts' ) 来获取 post 页面的 ID,并试图从那里找到一种方法得到最后一个post的标题,但至今没有成功。
有没有简单的方法可以做到这一点?
你是说 latest/most 最近 post 吗?
这对你有用吗?
<?php
$args = array(
'posts_per_page' => 1,
'orderby' => 'date',
'order' => 'DESC'
);
$post = get_posts( $args );
$latest_post_title = $post[0]->post_title;
echo $latest_post_title;
?>
或者这可能更轻一些,不确定,但它们做的事情几乎相同。
<?php
$args = array(
'numberposts' => 1,
);
$recent = wp_get_recent_posts($args);
$last_post_title = $recent[0]['post_title'];
echo $last_post_title;
?>
试一试:
echo current( wp_get_recent_posts( array('numberposts' => 1, 'post_status' => 'publish') ) )['post_title'];
我有一个 post 页面和一个不同的静态主页,以及其他常用页面,例如关于、赞助商。
我试图在所有页面的 header 中包含站点名称和最后一个 post 的标题。我尝试了不同的函数(the_title()、get_the_title())。它在 post 页面中运行良好,但对于所有剩余的页面,我得到页面的标题("About" 或 "Home" 或 "Sponsors")。
我知道到目前为止我使用的函数可能只在循环内工作,但想知道是否有某种全局方法可以让最后一个 post 的标题随处可用。
我必须:$posts_page = get_option( 'page_for_posts' ) 来获取 post 页面的 ID,并试图从那里找到一种方法得到最后一个post的标题,但至今没有成功。
有没有简单的方法可以做到这一点?
你是说 latest/most 最近 post 吗?
这对你有用吗?
<?php
$args = array(
'posts_per_page' => 1,
'orderby' => 'date',
'order' => 'DESC'
);
$post = get_posts( $args );
$latest_post_title = $post[0]->post_title;
echo $latest_post_title;
?>
或者这可能更轻一些,不确定,但它们做的事情几乎相同。
<?php
$args = array(
'numberposts' => 1,
);
$recent = wp_get_recent_posts($args);
$last_post_title = $recent[0]['post_title'];
echo $last_post_title;
?>
试一试:
echo current( wp_get_recent_posts( array('numberposts' => 1, 'post_status' => 'publish') ) )['post_title'];