Obtener custom post type por categoría en una plantilla de página
He creado un custom post type con categorías y subcategorías, lo que necesito hacer es listar los títulos de las entradas e imágenes para una subcategoría o categoría específica en una plantilla de página.
He llegado hasta el punto de obtener todos los elementos listados en el custom post type, pero no estoy seguro de cómo continuar... cualquier ayuda es apreciada.
<?php
$args = array( 'post_type' => 'portfolio', 'posts_per_page' => 10 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
the_title();
echo '<div class="entry-content">';
the_content();
echo '</div>';
endwhile;
?>
La función que crea el custom post type y la taxonomía se ve así:
<?php
// CUSTOM POST TYPE 1
add_action('init', 'portfolio_register');
function portfolio_register() {
$args = array(
'label' => __('Portfolio'),
'singular_label' => __('Portfolio'),
'public' => true,
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => true,
'supports' => array('title', 'editor', 'thumbnail')
);
register_taxonomy("galleries", array("portfolio"), array(
"hierarchical" => true,
"label" => "Galerías",
"singular_label" => "Galerías",
"rewrite" => true)
);
register_post_type( 'portfolio' , $args );
}
add_action("admin_init", "admin_init");
add_action('save_post', 'save_portfolio_options');
add_action('save_post', 'save_portfolio_single_options');
function admin_init(){
add_meta_box("gallerymeta", "Opciones de Galería", "portfolio_meta_options", "portfolio", "normal", "low");
add_meta_box("portfoliometa", "Opciones del Elemento de Portfolio", "portfolio_single_meta_options", "portfolio", "side", "low");
}
function portfolio_meta_options(){
global $post;
$custom = get_post_custom($post->ID);
$excerpt = $custom["excerpt"][0];
$info = $custom["info"][0];
$linkto = $custom["linkto"][0];
?>

Esta es una versión de una función que estoy usando en el framework en el que trabajo, con HTML de ejemplo reemplazando otra función que contiene algo similar.
// Loop personalizado
function arrr_custom_loop( $r_type = 'post', $r_post_num, $r_tax = 'category', $r_terms = 'featured' ) {
$args = array(
'showposts' => $r_post_num,
'tax_query' => array(
array(
'post_type' => $r_type,
'taxonomy' => $r_tax,
'field' => 'slug',
'terms' => array(
$r_terms
),
)
)
);
query_posts( $args );
if (have_posts())
while ( have_posts() ) : the_post();
$more = 0;
?>
<article>
<header class="pagetitle">
<?php if ( is_singular() ) { ?>
<h1><?php the_title(); ?></h1>
<?php } else { ?>
<h2 class="entry"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<?php } ?>
</header>
<div class="content_wrapper">
<div class="content">
<?php the_content(); ?>
</div>
</div>
<?php if ( comments_open() && ! post_password_required() ) { ?>
<div class="comments_wrapper">
<div class="comments">
<?php comments_template(); ?>
</div>
</div>
<?php } ?>
</article>
<?php endwhile;
wp_reset_query();
}
Entonces simplemente usarías la función con los argumentos creados:
arrr_custom_loop( 'portfolio', 10, 'galleries', 'pirates' );

Puedes obtenerlo si tienes/conoces el slug de la categoría/subcategoría...
Solo pásalo en el array de argumentos para query_posts.
$args = array( 'post_type' => 'portfolio', 'posts_per_page' => 10 ,'taxonomy_name'=>'slug de la categoría/subcategoría');
query_posts($args);

Parece que no funciona, sí conozco los slugs, pero esto muestra todas las publicaciones dentro de portfolio. He publicado la función que crea el tipo de publicación personalizado arriba por si ayuda. Las categorías son galerías y la que estoy intentando extraer es aerial.

He utilizado esto antes para hacer más de lo que necesitas, pero si eliminas la segunda taxonomía, te listará todas las publicaciones en una categoría determinada:
<?php
// configurar taxonomías
$tax_one = 'project_category';
$tax_two = 'brand';
$post_type = 'project';
$categories = get_categories( array(
'type' => $post_type,
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 0,
'hierarchical' => 1,
'taxonomy' => $tax_one ));
foreach ( $categories as $category ) : // listar todas las categorías
echo '<li><a href="'.get_term_link( $category->slug, $tax_one ).'">'.$category->name.'</a><ul>'?>
<?php $terms = get_terms( $tax_two, array( 'hide_empty' => 0 ) );
foreach ( $terms as $term ) : // listar todas las marcas en cada categoría
$myquery['tax_query'] = array(
array(
'taxonomy' => $tax_one,
'terms' => array($category->slug),
'field' => 'slug',
),
array(
'taxonomy' => $tax_two,
'terms' => array($term->slug),
'field' => 'slug',
)
);
$the_posts = new WP_Query($myquery);
if ( $the_posts->have_posts() ) : // si hay publicaciones en la marca y categoría actual, mostrarla
echo '<li><a href="'.get_term_link( $term->slug, $tax_two ).'">'.$term->name.'</a></li>';
endif;
endforeach; ?>
<?php echo '</ul></li>';
endforeach; ?>
Así que ajustándolo para tu situación:
<?php
// configurar taxonomías
$tax_one = 'category';
$post_type = 'portfolio';
$categories = get_categories( array(
'type' => $post_type,
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => 0,
'hierarchical' => 1,
'taxonomy' => $tax_one ));
foreach ( $categories as $category ) : // listar todas las categorías
echo '<li><a href="'.get_term_link( $category->slug, $tax_one ).'">'.$category->name.'</a><ul>'?>
<?php $the_posts = new WP_Query($myquery);
if ( $the_posts->have_posts() ) : // si hay publicaciones en la categoría actual, mostrarlas
foreach($the_posts as $post) :
echo '<li>Tu contenido de publicación aquí</li>';
endforeach;

La respuesta de Rajeev funcionó para mí usando tu código. En una instalación limpia, hice lo siguiente:
- Creé un functions.php que contenía solo tu función
portfolio_register
y el hookadd_action
que la llama - Creé dos galerías - "aérea" y "no aérea"
- Creé cuatro portafolios - "aérea 1", "aérea 2", "no aérea" y "sin galería", asignándolos a las galerías que sus nombres implican (o ninguna, en el caso de "sin galería")
- Creé
index.php
que contenía solo el primer bloque de código que pegaste. El único cambio que hice fue agregar'galleries'=>'aérea'
a tu variable$args
:
$args = array( 'post_type' => 'portfolio', 'posts_per_page' => 10, 'galleries'=>'aérea' );
Solo se mostraron "aérea 1" y "aérea 2".
¿Hay alguna posibilidad de que tu código no se esté ejecutando (¿quizás estás usando una plantilla diferente)?
