Не получается вывести посты из кастомной таксономии.

Не получается вывести посты из кастомной таксономии.

Создал новый post_type = 'custom_portfolio':

function custom_portfolio_post() {  
	register_post_type( 'custom_portfolio',         
		array('labels' => array(
			'name' => __('Примеры работ', 'jointswp'), 
			'singular_name' => __('Custom Work', 'jointswp'), 
			'all_items' => __('Все работы', 'jointswp'),
			'add_new' => __('Добавить новую', 'jointswp'), 
			'add_new_item' => __('Добавить новый пример работы', 'jointswp'), 
			'edit' => __( 'Edit', 'jointswp' ), 
			'edit_item' => __('Edit Post Types', 'jointswp'), 
			'new_item' => __('New Post Type', 'jointswp'), 
			'view_item' => __('View Post Type', 'jointswp'), 
			'search_items' => __('Search Post Type', 'jointswp'), 
			'not_found' =>  __('Nothing found in the Database.', 'jointswp'), 
			'not_found_in_trash' => __('Nothing found in Trash', 'jointswp'), 
			'parent_item_colon' => ''
			), 
			'description' => __( 'This is the portfolio post', 'jointswp' ), 
			'public' => true,
			'publicly_queryable' => true,
			'exclude_from_search' => false,
			'show_ui' => true,
			'query_var' => true,
			'menu_position' => 10,
			'menu_icon' => 'dashicons-format-gallery',
			'rewrite'   => array( 'slug' => 'custom-portfolio', 'with_front' => false ),
			'has_archive' => 'custom_portfolio',
			'capability_type' => 'post',
			'hierarchical' => false,            
			'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'sticky', 'post-formats'),
			'taxonomies' => array('category', 'custom_gallery')
		) 
	); 

	/* Цепляю таксономию 'custom_gallery' */    
	register_taxonomy_for_object_type('category', 'custom_gallery');    

}

/*Регистрирую таксономию*/
register_taxonomy( 'custom_gallery', 
		array('custom_portfolio'), /* if you change the name of register_post_type( 'custom_type', then you have to change this */
		array('hierarchical' => true,     /* if this is true, it acts like categories */             
			'labels' => array(
				'name' => __( 'Разделы галерей', 'jointswp' ), /* name of the custom taxonomy */
				'singular_name' => __( 'Раздел галерей', 'jointswp' ), /* single taxonomy name */
				'search_items' =>  __( 'Искать разделы галерей', 'jointswp' ), /* search title for taxomony */
				'all_items' => __( 'Все разделы галарей', 'jointswp' ), /* all title for taxonomies */
				'parent_item' => __( 'Parent Custom Category', 'jointswp' ), /* parent title for taxonomy */
				'parent_item_colon' => __( 'Parent Custom Category:', 'jointswp' ), /* parent taxonomy title */
				'edit_item' => __( 'Редактировать раздел галерей', 'jointswp' ), /* edit custom taxonomy title */
				'update_item' => __( 'Update Custom Category', 'jointswp' ), /* update title for taxonomy */
				'add_new_item' => __( 'Добавить новый раздел галерей', 'jointswp' ), /* add new title for taxonomy */
				'new_item_name' => __( 'New Custom Category Name', 'jointswp' ) /* name title for taxonomy */
			),
			'show_admin_column' => true, 
			'show_ui' => true,
			'query_var' => true,
			'rewrite' => array( 'slug' => 'custom-gallery' ),
		)
	);

/*Инит*/
add_action( 'init', 'custom_portfolio_post');

После этого в админке появлятся панель "ПРИМЕРЫ РАБОТ" и пункт "Разделы галерей". Создаю соответственно несколько разделов: дизайн проекты, отделка, корпусная мебель итд. И им присваиваю записи.

При попытке получить посты для каждого раздела через get_posts() получаю фигу.

$args_posts = array(
				'numberposts' => 20,
				'category' => id_раздела,
				'post_type'=> 'custom_portfolio'
			);

$posts = get_posts( $args_posts );

if($posts) {
	foreach ($posts as $post) {
		the_title(); ?
	}
}
else {
	echo "Здесь нет постов";
}

В чем может быть проблема? Когда получаю посты для обычных "Рубрик" все получается. Как только приходит айди категории из созданной таксономии - все, пустота.

Заранее спасибо

Заметки к вопросу:
campusboy 5.7 лет назад

Потому что custom_gallery не category. Это же разные таксономии. Вот он ничего и не выдаёт, так как ты указываешь "дай мне category с id таким". А такой рубрики нет, потому что она custom_gallery. Используй wp_query для этого, смотри там пункт "Параметры таксономий". В целом, get_posts может принимать те же параметры, что и wp_query, потому можешь их и там использовать.

Goosevkir 5.7 лет назад

Да, это я понимаю, мне бы на примере чтоли, я уже и wp-query() пробовал, и get_posts(), только вот решения не нашел.

Вообще неужели такая крутая CMS как WP не предоставляет какого-то нормального решения? не верю!

Goosevkir 5.7 лет назад

Я правильно понимаю, что таксономия - это кастомный тип РУБРИК? У разделов внутри таксономии ведь тоже есть свои ID. Вот как по ним вытащить посты?

Goosevkir 5.7 лет назад

В общем, спасибо! Вопрос решился вот так:

$args = array(
				'post_type' => 'custom_portfolio',
				'custom_gallery' => 'taxonomy-slug'
			);

			$query = new WP_Query( $args );

Хорошо, что зарегался здесь)

campusboy 5.7 лет назад

Молодец, что разобрался!