简体   繁体   中英

Getting posts from category of custom post type Wordpress

I have the code below, used to to create a category. How can i get posts using this category ? I can get the id of this category, but can`t get all the posts of the category.

function create_taxonomy()
{
    $labels= array(
    'name' => 'Kategórie',
    'singular_name' => 'Kategórie',
    'search_items' => 'Vyhladať kategórie',
    'all_items' => 'Všetky kategórie',
    'edit_item' => 'Upraviť',
    'update_item' => 'Aktualizovať',
    'add_new_item' => 'Pridať',
    'new_item_name' => 'Nový názov',
    'menu_name' => 'Kategórie',
    );
    register_taxonomy('Categories', array('service'), array(
    'hierarchical' => true,
    'labels' => $labels,
    'show_ui' => true,
    'query_var' => true,
    'rewrite' => array('slug' => 'categories')
    ));
}
add_action('init','create_taxonomy',0);

here is post type

https://pastebin.com/0eAPeBMr

The below code should do the trick.

$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        array(
            'taxonomy' => 'categories',
            'field' => 'slug', //can be set to ID
            'terms' => 'category-slug' //if field is ID you can reference by cat/term number
        )
    )
);
$query = new WP_Query( $args );

Set the ' taxonomy ' to your category taxonomy and change the terms to your category-slug. If you want to do it by Category ID, then change the field value to "term_id" and provide the category ID in terms value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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