Last active
June 1, 2018 17:39
-
-
Save Garconis/fcda9499bc1608037625ece68a35588d to your computer and use it in GitHub Desktop.
WordPress | Shortcode to output a loop of content of a custom post type
This file contains hidden or 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 | |
// create shortcode to list all Featured Itineraries | |
add_shortcode( 'all-featured-itineraries', 'fs_all_featured_itineraries_shortcode' ); | |
function fs_all_featured_itineraries_shortcode( $atts ) { | |
ob_start(); | |
// Query posts from the database. | |
$options = array( | |
// Arguments for your query. | |
'post_type' => 'collections', | |
'posts_per_page' => -1, | |
'meta_key' => 'featured-product', | |
'meta_value' => '1', | |
); | |
$query = new WP_Query( $options ); | |
// // Check that we have query results | |
if ( $query->have_posts() ) { | |
// we have posts, so lets wrap them | |
echo'<div class="all-featured-itineraries">'; | |
// Start looping over the query results. | |
while ( $query->have_posts() ) { | |
// Set up post data. | |
$query->the_post(); | |
// Set the featured image variable | |
$feat_image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'large')[0]; | |
// get the excerpt and content | |
$collection_excerpt = get_the_excerpt(); | |
$collection_content = get_the_content(); | |
/* Contents of the queried post results go here. */ | |
echo '<div class="c-card collection-card"> | |
<a href="'. get_permalink() .'"> | |
<div class="collection-card--header" style="background-image:url('. $feat_image .');"> | |
<span class="collection-author-nickname">'. get_avatar( get_the_author_meta( 'ID' ), 30 ) .' by '. get_the_author_meta( 'display_name' ) .'</span> | |
</div> | |
<span class="new-card"> | |
<div class="collection-card--name"> | |
<h3>'. get_the_title() .'</h3> | |
</div> | |
<div class="collection-card--title">'; | |
if ( !empty( $collection_excerpt ) ) { | |
echo $collection_excerpt; | |
} | |
else { | |
echo $collection_content; | |
} | |
echo '</div> | |
<div class="collection-card--follow-button"></div> | |
</span> | |
</a> | |
</div>'; | |
// close the loop WHILE | |
} | |
wp_reset_postdata(); | |
// close post wrapper | |
echo '</div>'; | |
$myvariable = ob_get_clean(); | |
return $myvariable; | |
// close the query IF | |
} | |
// ELSE it cant find ANY posts that match | |
else { | |
echo '<div class="no-featured-collections"><h4>We currently have no Featured Itineraries to show you.</h4></div>'; | |
// close the query ELSE */ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment