Last active
August 13, 2023 14:18
Shortcode: CategoryPosts - Content Hub
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// WordPress Shortcode - Content Hub: Lists all posts for the first category of a post | |
// Need help: https://bloggerpilot.com/en/content-hub-wordpress/ | |
function bp_categoryposts() { | |
// Get first category | |
$categories = get_the_category(); | |
if ( ! empty( $categories ) ) { | |
$category = $categories[0]->name; | |
} | |
// The query | |
$the_query = new WP_Query( array( | |
'category_name' => $category, | |
'posts_per_page' => 100 | |
) ); | |
// A little Style | |
$list .= '<style>'; | |
$list .= 'ul.categoryposts {list-style-type:none;}'; | |
$list .= 'ul.categoryposts li::before {'; | |
$list .= ' content: "🎂 ";'; | |
$list .= '}'; | |
$list .= '</style>'; | |
// The Loop | |
if ( $the_query->have_posts() ) { | |
$list .= '<span class="h2 wp-block-heading">'.$category.'</span>'; | |
$list .= '<ul class="categoryposts">'; | |
while ( $the_query->have_posts() ) { | |
$the_query->the_post(); | |
$list .= '<li><a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_title() .'</a></li>'; | |
} | |
} | |
$list .= '</ul>'; | |
return $list; | |
/* Restore original Post Data */ | |
wp_reset_postdata(); | |
} | |
// Add a shortcode | |
add_shortcode('categoryposts', 'bp_categoryposts'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment