简体   繁体   English

如何根据类别名称从wordpress数据库中选择所有帖子?

[英]How to select all the posts from wordpress database based on category name?

First off, I know this question has been asked many times before and I found quite a few of them on this site and Google. 首先,我知道这个问题已经被问过很多次了,我在本网站和Google上发现了很多问题。

example: How does Wordpress link posts to categories in its database? 示例: Wordpress如何将帖子链接到其数据库中的类别?

However, I can't really understand how to find all the posts based on their category names from wordpress database. 但是,我真的无法理解如何从wordpress数据库中根据类别名称查找所有帖子。

Example: I have a category name called 'restaurants' . 示例:我有一个名为'restaurants'的类别名称。

And I have a few posts under that category. 我在该类别下有几篇文章。

What is the correct query for this? 正确的查询是什么?

also, in the link above, I noticed that the provided answer mentions that the wordpress database might change, so what is the best query to use to make sure these changes doesn't break my code? 另外,在上面的链接中,我注意到所提供的答案提到wordpress数据库可能会发生变化,那么用来确保这些变化不会破坏我的代码的最佳查询是什么?

Thanks in advance. 提前致谢。

EDIT: 编辑:

Here is one example that i tried which doesn't work. 这是我尝试的一个不起作用的示例。

<?php 

require_once(ABSPATH . 'wp-config.php');
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysqli_select_db($connection, DB_NAME);

$custom_query = new WP_Query('cat=9'); //your category id 
while($custom_query->have_posts()) : $custom_query->the_post(); ?>

    //loop items go here

<?php endwhile; ?>
<?php wp_reset_postdata(); // reset the query ?>

EDIT 2: 编辑2:

I tried this code which doesn't do anything. 我尝试了此代码,但没有执行任何操作。 Just a blank page: 只是一个空白页:

<?php

require_once('../wp-config.php');
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysqli_select_db($connection, DB_NAME);



$args=array(
'post_type' => 'post',
'post_status' => 'publish',
'category_name' => 'restaurants');

$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
    echo '<div class="Entradas">'.get_the_title().'</div>';
endwhile;
}
wp_reset_query();



?>

This worked fine: 这工作正常:

  $myposts = get_posts(array(
  'showposts' => -1, //add -1 if you want to show all posts
  'post_type' => 'offer',
  'tax_query' => array(
              array(
                    'taxonomy' => 'offer_cat',
                    'field' => 'slug',
                    'terms' => 'restaurants' //pass your term name here
                      )
                    ))
                   );

    foreach ($myposts as $mypost) {
    // echo $mypost->post_title . '<br/>';
    // echo $mypost->post_content . '<br/>';
    // echo  $mypost->ID . '<br/><br/>';
    echo '<li class="faq"> <p class="title"><a href="' . get_permalink($mypost) . '">' . $mypost->post_title . '</a></p></li>';} 

I hope it helps others. 我希望它可以帮助其他人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM