怎么用wordpress API和php做到这一点

I am really a newbie in Wordpress and php. I created a theme for my website as follows:

enter image description here

I think my question is clear: in wordpress admin page I have four categories: 1,2,3,4. I want last 2 posts in category 1 to be displayed in section (div) 1 (shown above), last 2 posts in category 2 to be displayed in section (div) 2, and so on.
As I said, I am novice and I faced a tons of functions in Wordpress documentation.
for example I used the code below inside index.php (of my custom theme) in section 2 which outputs: "Sorry, no posts matched your criteria."

   <?php 
                    $args = array( 'post' => 'post', 'posts_per_page' => 1,'category_name'=>'تازه ها');
                    $the_query = new WP_Query( $args ); 
                    ?>
                    <?php 
                    if ( $the_query->have_posts() ) : ?>
                    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
                    <h2><?php the_title(); ?></h2>
                    <div class="entry-content">
                    <?php the_content(); ?> 
                    </div>
                    <?php endwhile; ?>
                    <?php wp_reset_postdata(); ?>
                    <?php else:  ?>
                    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
                    <?php endif; 
                ?>

Please give a piece of code to do this.

dongmen5867
dongmen5867 我在帖子中将标签更改为类别,并且还更改了代码,但仍然失败,尽管一切似乎都没问题
接近 6 年之前 回复

1个回答

This should work:

$posts = get_posts ("cat=1&showposts=2");
if ($posts) 
{
    foreach ($posts as $post):
    setup_postdata($post); ?>
    <h2><?php the_title(); ?></h2>
<?php endforeach;
}

Change cat=1 to the id of each of the four categories.

dsyo9700
dsyo9700 数字1是要在get_posts中使用的类别ID
接近 6 年之前 回复
dongleiqiao2107
dongleiqiao2107 你是什​​么意思,tag_ID = 1是类别ID?
接近 6 年之前 回复
douji4223
douji4223 这也可行,但如果你转到wordpress的后端并编辑帖子类别,链接就会像http://example.com/wp-admin/edit-tags.php?action=edit&taxonomy=category&tag_ID= 1&post_type = post,tag_ID = 1是类别ID。
接近 6 年之前 回复
doudou5101
doudou5101 也许透过这个? $ category_id = get_cat_ID('类别名称');
接近 6 年之前 回复
dsvd407787736
dsvd407787736 如何获得任何类别的ID?
接近 6 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐