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

时间:2019-01-06 13:39:50

标签: php mysql wordpress

首先,我知道这个问题已经被问过很多次了,我在本网站和Google上发现了很多问题。

示例:How does Wordpress link posts to categories in its database?

但是,我真的不明白如何根据wordpress数据库中的类别名称查找所有帖子。

示例:我有一个名为'restaurants'的类别名称。

我在该类别下有几则帖子。

对此的正确查询是什么?

另外,在上面的链接中,我注意到所提供的答案提到wordpress数据库可能会更改,那么最好使用什么查询来确保这些更改不会破坏我的代码?

谢谢。

编辑:

这是我尝试的一个不起作用的示例。

<?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 ?>

编辑2:

我尝试了此代码,但没有执行任何操作。只是一个空白页:

<?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();



?>

1 个答案:

答案 0 :(得分:0)

这很好:

  $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>';} 

我希望它可以帮助其他人。

相关问题