根据类别 ID 获取最近 post 的第一段
Getting first paragraph of most recent post based on category ID
我已经有一段时间没有使用 PHP 和 WordPress 了,所以我有点生疏了。我想要做的是在 WordPress 站点的类别下显示最近 post 的开头段落。根据我所做的一些研究,我编译了这段代码:
<?php
$category_id = get_cat_ID('Downtown News');
$post = get_posts( $category_id );
if( !empty( $post ) ) {
setup_postdata( $post );
?><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php the_excerpt();
} ?>
<?php
$post = $wp_query->post;
setup_postdata( $post );
?>
我有获取我想要的类别 ID 的代码,我有显示最新文章第一段的代码。但是,代码似乎不起作用。显示的是"uncategorized"类postings下的第一段,这不是我想要的。我怎样才能修复我拥有的东西以使其获得正确的类别?
我遇到了与你类似的问题,也许这个对你有用
注意 $category_id
是从 get_cat_ID()
函数中提取出来的,这告诉我你不知道 cat_id
,你可以转到你创建市中心新闻的类别,移动将鼠标悬停在上面以显示 url 地址,它会告诉您类别 ID,找到该数字并替换行:
query_posts('cat='.$category_id.'&posts_per_page=1');
(以99为例)
query_posts('cat=99&posts_per_page=1');
<?php
global $post;
$category_id = get_cat_ID('Downtown News');
query_posts('cat='.$category_id.'&posts_per_page=1');
if ( have_posts() ) {
?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php the_excerpt();
}
wp_reset_query();
?>
您的起点是正确的:get_posts
,但是您没有正确的参数。所以请尝试以下操作:
<?php
$args = array(
'category' => 'CAT_ID_1,CAT_ID_2',
'orderby' => 'post_date',
'order' => 'DESC');
$posts_array = get_posts( $args );
?>
从函数参考我们知道:
The category parameter needs to be the ID of the category, and not the
category name
这意味着您可以拥有一个或多个类别 ID(以逗号分隔)。
可以找到所有参数的列表here。
我已经有一段时间没有使用 PHP 和 WordPress 了,所以我有点生疏了。我想要做的是在 WordPress 站点的类别下显示最近 post 的开头段落。根据我所做的一些研究,我编译了这段代码:
<?php
$category_id = get_cat_ID('Downtown News');
$post = get_posts( $category_id );
if( !empty( $post ) ) {
setup_postdata( $post );
?><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php the_excerpt();
} ?>
<?php
$post = $wp_query->post;
setup_postdata( $post );
?>
我有获取我想要的类别 ID 的代码,我有显示最新文章第一段的代码。但是,代码似乎不起作用。显示的是"uncategorized"类postings下的第一段,这不是我想要的。我怎样才能修复我拥有的东西以使其获得正确的类别?
我遇到了与你类似的问题,也许这个对你有用
注意 $category_id
是从 get_cat_ID()
函数中提取出来的,这告诉我你不知道 cat_id
,你可以转到你创建市中心新闻的类别,移动将鼠标悬停在上面以显示 url 地址,它会告诉您类别 ID,找到该数字并替换行:
query_posts('cat='.$category_id.'&posts_per_page=1');
(以99为例)
query_posts('cat=99&posts_per_page=1');
<?php
global $post;
$category_id = get_cat_ID('Downtown News');
query_posts('cat='.$category_id.'&posts_per_page=1');
if ( have_posts() ) {
?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php the_excerpt();
}
wp_reset_query();
?>
您的起点是正确的:get_posts
,但是您没有正确的参数。所以请尝试以下操作:
<?php
$args = array(
'category' => 'CAT_ID_1,CAT_ID_2',
'orderby' => 'post_date',
'order' => 'DESC');
$posts_array = get_posts( $args );
?>
从函数参考我们知道:
The category parameter needs to be the ID of the category, and not the category name
这意味着您可以拥有一个或多个类别 ID(以逗号分隔)。
可以找到所有参数的列表here。