Skip to content

Instantly share code, notes, and snippets.

@nfsarmento
Last active September 22, 2023 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nfsarmento/545672c3205a36c488aecb502fa79a77 to your computer and use it in GitHub Desktop.
Save nfsarmento/545672c3205a36c488aecb502fa79a77 to your computer and use it in GitHub Desktop.
WordPress shortoce to show Custom Post Type
<?php
/**
*
* Usage [newscpt posts_per_page="4" term="4"] .
* Change post_type to your CPT name
* Change taxonomy to your taxonomy name
*
*/
// @codingStandardsIgnoreStart
function ns_cpt_grid_news_shortcode( $atts ) {
ob_start();
// Parse your shortcode settings with it's defaults
$atts = shortcode_atts( array(
'posts_per_page' => '-1',
'term' => ''
), $atts, 'newscpt' );
// Extract shortcode atributes
extract( $atts );
// Define query
$query_args = array(
'post_type' => 'news', // 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' => 'category_news',
'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() ) {
?>
<div class="grid__container_three_columns">
<?php
while ( $custom_query->have_posts() ) {
$custom_query->the_post();
$first_term_name = get_the_terms( $post->ID, 'category_news' )[0]->name;
$url = get_the_post_thumbnail_url( get_the_ID(), 'full' );
//var_dump( $first_term_name );
?>
<div class="grid__item grid__items_sc work__sc">
<div class="grid__item_image">
<a href="<?php echo get_permalink(); ?>"><img width="100%" src="<?php echo $url ?>"/></a>
</div>
<div class="grid__item_descr">
<a href="<?php echo get_permalink(); ?>"><p class="title-st"><?php echo get_the_title(); ?></p></a>
<a href="<?php echo get_permalink(); ?>"><p class="title-st"><?php echo esc_attr( $first_term_name ); ?></p></a>
</div>
</div>
<?php
}
?>
</div>
<?php
// Restore data
wp_reset_postdata();
}
// Return your shortcode output
return ob_get_clean();
}
add_shortcode( 'newscpt', 'ns_cpt_grid_news_shortcode' );
// @codingStandardsIgnoreEnd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment