How can I turn this PHP snippet into a Wordpress shortcode? -


this music website multiple artist pages - 1 page per artist. new content added post wordpress tag denote artist. can add wordpress loop on each artist page show posts filtered artist's tag.

i've got filtered loop working correctly, unfortunately it's hardwritten inside page template's html, it's filtering 1 tag. don't want create new page template each artist, i'd add functions.php file instead, can instead create new shortcode each artist.

here's current code in page template, filters loop posts our seefour tag:

<?php query_posts( "tag=seefour" ); if ( have_posts() ) { ?>   <?php while ( have_posts() ) { ?>     <?php the_post(); { ?>     <div class="jd-box">       <a href="<?php the_permalink(); ?>">         <?php the_post_thumbnail( ); ?>         <div class="jd-overlay"></div>         <div class="jd-overlay-text">           <?php the_title(); ?>         </div>       </a>     </div> <?php } ?> <?php } ?> <?php } ?> 

i'm assuming best option turn seefour shortcode inside functions.php file - how can achieve this?

bonus question: sustainable in long run (with 30-50+ artists) or cause lot of redundant code? open suggestions...

p.s. know kind of question has been answered (starting raw php), since i'm starting mix of html/php (and i'm php newb), can't work. apologies asking again.

first of all, should never ever use query_posts(). internal wordpress function create , maintain main wordpress cycle. using it, can crash site in unpredictable manner. should use get_posts() or wp_query instead.

to have custom shortcode, add following functions.php:

function showtag_shortcode( $atts ) {     $atts = shortcode_atts( array(         'tag' => '', // default value.     ), $atts );      $posts = get_posts( 'tag=' . $atts['tag'] );     if ( $posts ) {         $output = '';         foreach ( $posts $post ) {             setup_postdata( $post );             $output .= '<div class="jd-box">';             $output .= '<a href="' . get_the_permalink( $post ) . '">';             $output .= get_the_post_thumbnail( $post );             $output .= '<div class="jd-overlay"></div>';             $output .= '<div class="jd-overlay-text">';             $output .= get_the_title( $post );             $output .= '</div>';             $output .= '</a>';             $output .= '</div>';         }     } else {         $output = 'no data';     }     wp_reset_postdata();      return $output; }  add_shortcode( 'showtag', 'showtag_shortcode' ); 

this function created [showtag] shortcode 1 parameter: tag. can use shortcode on page follows:

[showtag tag="seefour"] [showtag tag="disco"] 

etc. have posts relevant tags shown in place of shortcode.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -