按类别公告类型分开

时间:2017-11-15 作者:Kristopher Danday

假设我有这样的数据

$query = new WP_Query(array(\'post_type\' => \'Hotels\',\'posts_per_page\'=>-1));
但我希望它通过特定字段(例如位置)将它们分开,并触发这种输出

<table>
<thead>
   <tr>
    <td>Japan</td>
    <td>China</td>
   </tr>
</thead>
<tbody>
<tr>
<td>Hotel from China</td>
<td>Hotel from Japan</td>
</tr>
<tr>
<td>Hotel from China</td>
<td>Hotel from Japan</td>
</tr>
</tbody>
</table>

1 个回复
SO网友:HeroWeb512

要获取具有特定类别的自定义帖子类型,请使用自定义分类法

注册自定义帖子类型的分类法名称,如位置,然后在添加新帖子时为每个帖子分配位置。下面是代码的示例

  add_action( \'init\', \'hotels_my_taxonomy\');
  function hotels_my_taxonomy(){
 // custom post type taxonomies
    $labels = array(
    \'name\' => \'Locations\',
    \'singular_name\' => \'Location\',
    \'add_new\' => \'Add Location\',
    \'add_new_item\' => \'Add New Location\',
    \'all_items\' => \'All Locations\',
    \'edit_item\' => \'Edit Item\',
    \'new_item\' => \'New Item\',
    \'view_item\' => \'View Item\',
    \'update_item\' => \'Update Location\',
    \'search_items\' => \'Search Locations\',
    \'not_found\' => \'No record found\',
    \'not_found_in_trash\' => \'No items found in trash\',
    \'parent_item_colon\' => \'Parent Item\',
    \'menu_name\' => \'Locations\'
    );
    $args = array(
        \'labels\' => $labels,
        \'hierarchical\' => true,
        \'has_archive\' => true,
        \'rewrite\' => array(\'slug\' => \'hotels_location\'),
        \'show_ui\' => true,
        \'show_admin_column\' => true,
        \'query_var\' => true,
        );
        register_taxonomy(\'hotels_location\', array(\'hotels\'), $args);
}
然后创建分类模板页面“taxonomy-hotels\\u位置”。php“并添加查询以获取具有此类别名称的帖子

   $cat_name = single_cat_title;
   $args = array( \'category_name\' => $cat_name, \'posts_per_page\' => 12, \'order\'=> \'ASC\', \'post_type\' => \'hotels\', \'paged\' => $paged);
所有的工作都完成了。祝你好运

结束