使用 wordpress 中的参数将短代码添加到自定义 post

Adding shortcode to custom post with parameters in wordpress

我添加了这个名为“candidates”的自定义post,我想生成一个带有参数的短代码[candidate],使其成为[candidates id="123"]。到目前为止,这是我的代码。我想显示缩略图、标题和一个显示“查看评论”的按钮,该按钮重定向到单个 post.

// >> Create Shortcode to Display Movies Post Types

函数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');

//简码代码到此结束

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');