Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress shortoce to show Custom Post Type
<?php
/**
*
* Usage [workcpt posts_per_page="4" term="4"] .
* I'm using MultiPostThumbnails plugin (line 63) to fetch a second fetaure image - if you are not using the plugin please replace that with get get_the_post_thumbnail_url(get_the_ID(),'full');
* Change post_type to your CPT name
* Change taxonomy to your taxonomy name
*
*/
// @codingStandardsIgnoreStart
function ns_cpt_grid_work_shortcode( $atts ) {
// Parse your shortcode settings with it's defaults
$atts = shortcode_atts( array(
'posts_per_page' => '-1',
'term' => ''
), $atts, 'workcpt' );
// Extract shortcode atributes
extract( $atts );
// Define output var
$output = '';
// Define query
$query_args = array(
'post_type' => 'work', // Change this to the type of post you want to show
'posts_per_page' => $posts_per_page,
);
// Query by term if defined
if ( $term ) {
$query_args['tax_query'] = array(
array(
'taxonomy' => 'work_categories',
'field' => 'ID',
'terms' => $term,
),
);
}
// Query posts
$custom_query = new WP_Query( $query_args );
// Add content if we found posts via our query
if ( $custom_query->have_posts() ) {
// Open div wrapper around loop
$output .= '<div class="grid__container_three_columns">';
// Loop through posts
while ( $custom_query->have_posts() ) {
// Sets up post data so you can use functions like get_the_title(), get_permalink(), etc
$custom_query->the_post();
$first_term_name = get_the_terms( $post->ID, 'work_categories' )[0]->name;
//var_dump( $first_term_name );
// This is the output for your entry so what you want to do for each post.
$output .= '<div class="grid__item grid__items_sc work__sc">';
//$output .= '<div class="grid__item_image">' . get_the_post_thumbnail() . '</div>';
$output .= '<div class="grid__item_image">';
$output .= '<a href="'. get_permalink() .'"><img width="100%" src="'. MultiPostThumbnails::get_post_thumbnail_url(get_post_type(), "secondary-image", NULL, "secondary-featured-thumbnail" ) .'"/></a>';
$output .= '</div>';
$output .= '<div class="grid__item_descr">';
$output .= '<a href="'. get_permalink() .'"><p class="title-st">'. get_the_title() .'</p></a>';
$output .= '<a href="'. get_permalink() .'"><p class="title-st">'. esc_attr( $first_term_name ) .'</p></a>';
$output .= '</div>';
$output .= '</div>';
}
// Close div wrapper around loop
$output .= '</div>';
// Restore data
wp_reset_postdata();
}
// Return your shortcode output
return $output;
}
add_shortcode( 'workcpt', 'ns_cpt_grid_work_shortcode' );
// @codingStandardsIgnoreEnd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.