I would like to list all subcategories of the main category "Referenzliste" and include links to the posts within those subcategories. This is for a custom post type (referenzen). My script already outputs the subcategories, but it does not find the individual posts even they are published.
function verlinkte_artikel_referenzen($atts) {
// Attributsbehandlung
$atts = shortcode_atts(array(
'parent_cat' => 'Referenzliste',
'cpt' => 'referenzen'
), $atts, 'verlinkte_artikel_referenzen');
// Hole die übergeordnete Kategorie
$parent_category = get_term_by('name', $atts['parent_cat'], 'category');
if (!$parent_category) {
return 'Kategorie nicht gefunden.';
}
// Hole die Unterkategorien der übergeordneten Kategorie
$unterkategorien = get_terms(array(
'taxonomy' => 'category',
'child_of' => $parent_category->term_id,
'hide_empty' => false
));
if (empty($unterkategorien)) {
return 'Keine Unterkategorien gefunden.';
}
$output = '<div class="referenzen-list">';
foreach ($unterkategorien as $unterkategorie) {
$output .= '<h2>' . esc_html($unterkategorie->name) . '</h2>';
$output .= '<ul>';
$query = new WP_Query(array(
'post_type' => $atts['cpt'],
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'term_id',
'terms' => $unterkategorie->term_id
)
)
));
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$output .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
}
wp_reset_postdata();
} else {
$output .= '<li>Keine Artikel gefunden.</li>';
}
$output .= '</ul>';
}
$output .= '</div>';
return $output;
}
add_shortcode('verlinkte_artikel_referenzen', 'verlinkte_artikel_referenzen');
2
Answers
The Code is working right i had a typo in the CPT name.