Last active
February 20, 2023 12:37
-
-
Save diggeddy/41970526b34574a2a4c960869f14b12a to your computer and use it in GitHub Desktop.
Posts by Month shortcode
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 Snippet to create shortcode | |
// display nested list of posts by month year | |
function list_posts_by_month() { | |
$args = array( | |
'post_type' => 'post', | |
'posts_per_page' => -1, | |
'orderby' => 'date', | |
'order' => 'DESC' | |
); | |
$query = new WP_Query( $args ); | |
$posts_by_month = array(); | |
while ( $query->have_posts() ) { | |
$query->the_post(); | |
$post_month = get_the_date( 'F Y' ); | |
$posts_by_month[ $post_month ][] = array( | |
'title' => get_the_title(), | |
'permalink' => get_permalink() | |
); | |
} | |
wp_reset_postdata(); | |
$html = ''; | |
if ( ! empty( $posts_by_month ) ) { | |
$html = '<ul class="post-list">'; | |
foreach ( $posts_by_month as $month => $posts ) { | |
$html .= '<li>'; | |
$html .= '<input type="checkbox" name="post-month-toggle" id="' . sanitize_title( $month ) . '" />'; | |
$html .= '<label for="' . sanitize_title( $month ) . '">' . $month . ' (' . count( $posts ) . ')</label>'; | |
$html .= '<ul class="post-list__child">'; | |
foreach ( $posts as $post ) { | |
$html .= '<li><a href="' . $post['permalink'] . '">' . $post['title'] . '</a></li>'; | |
} | |
$html .= '</ul>'; | |
$html .= '</li>'; | |
} | |
$html .= '</ul>'; | |
} | |
return $html; | |
} | |
add_shortcode( 'post_cal', 'list_posts_by_month' ); | |
/* Add some CSS to make the post list toggle */ | |
.post-list__child { | |
display: none; | |
} | |
input[type="checkbox"][name="post-month-toggle"]:checked ~ .post-list__child { | |
display: block; | |
} | |
input[type="checkbox"][name="post-month-toggle"] { | |
opacity: 0; | |
position: absolute; | |
} | |
.post-list label { | |
cursor: pointer; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment