Eleni Calibat
Eleni Calibat

Reputation: 21

Adding shortcode to custom post with parameters in wordpress

I added this custom post named "candidates" and I wanted to generate a shortcode [candidate] with parameters to make it [candidates id="123"]. Here is my code so far. I wanted to display the thumbnail picture, title, and a button that says "see comments" that redirects to the single post.

// >> Create Shortcode to Display Movies Post Types

function diwp_create_shortcode_candidates_post_type(){

$args = array(
                'post_type'      => 'candidates',
                'posts_per_page' => '1',
                'publish_status' => 'published',
             );

$query = new WP_Query($args);

if($query->have_posts()) :

    while($query->have_posts()) :

        $query->the_post() ;
                 
    $result .= '<div class="candidates-item">';
    $result .= '<div class="candidates-poster">' . get_the_post_thumbnail() . '</div>';
    $result .= '<div class="candidates-name">' . get_the_title() . '</div>';
    $result .= '</div>';

    endwhile;

    wp_reset_postdata();

endif;    

return $result;            

}

add_shortcode( 'candidates', 'diwp_create_shortcode_candidates_post_type' );

// shortcode code ends here

Upvotes: 0

Views: 1814

Answers (1)

jayceegarcia
jayceegarcia

Reputation: 26

function recent_posts_function($atts){
  extract(
    shortcode_atts(
      array(
        'post_id' => '',
        // 'extra_param' => '', // you can add more parameters [candidates extra_param=""]
    ),
  $atts)
);

$args = array(
  //'p' => $post_id,                    // will accept single post id only
  'post__in' => explode(" ",$post_id),  // will accept multiple post_id separated by comma
  'post_type' => 'candidates',
  // 'posts_per_page' => $extra_param,  // extra_param added at shortcode_atts at top
  // get the Query Parameters here: https://developer.wordpress.org/reference/classes/wp_query/
);

$return_string = '';

$query = new WP_Query( $args );

if ($query->have_posts()) :
  $return_string .= '<ul>';
    while ($query->have_posts()) : $query->the_post();
      $return_string .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
      // $return_string .= ''; content na to
    endwhile;
  $return_string .= '</ul>';
  endif;

  wp_reset_postdata();
  return $return_string;
}

add_shortcode('candidates', 'recent_posts_function');

Upvotes: 1

Related Questions