How would I create a shortcode to display a custom post within a page or regular post?

I would like to create a shortcode that will extract information for a custom post, and display it within a Page or regular Post.

Specific use case: I have a custom post type “Film” for a film festival website. The films are displayed with their own single-film.php, but occasionally the site owners want to write a post or page that mentions a particular film, and would like to be able to pull snippets of the info that has already been entered (eg, Film name, booking info, etc). This would go in a “box” at the bottom of the post, and I’d like to make it easy for them by providing some sort of shortcode.

Read More

How would I go about doing this? Any recommended resources/tutorials to get me on the right track? What gotchas should I be aware of (eg, multiple loops in a post)?

Related posts

Leave a Reply

2 comments

  1. There are great tutorials about shortcodes all over the web and some good examples here

    but just to get you started:

    add_shortcode('film_q', 'film_shortcode_query');
    function film_shortcode_query($atts, $content){
      extract(shortcode_atts(array( // a few default values
       'posts_per_page' => '1',
       'post_type' => 'film',
       'caller_get_posts' => 1)
       , $atts));
    
      global $post;
    
      $posts = new WP_Query($atts);
      $output = '';
        if ($posts->have_posts())
            while ($posts->have_posts()):
                $posts->the_post();
                $out = '<div class="film_box">
                    <h4>Film Name: <a href="'.get_permalink().'" title="' . get_the_title() . '">'.get_the_title() .'</a></h4>
                    <p class="Film_desc">'.get_the_content().'</p>';
                    // add here more...
                $out .='</div>';
        /* these arguments will be available from inside $content
            get_permalink()  
            get_the_content()
            get_the_category_list(', ')
            get_the_title()
            and custom fields
            get_post_meta($post->ID, 'field_name', true);
        */
        endwhile;
      else
        return; // no posts found
    
      wp_reset_query();
      return html_entity_decode($out);
    }
    

    and to use it enter in any post/page:

    [film_q p=FILM_POST_ID]
    

    just change FILM_POST_ID to the actual Film post ID.

    Hope this helps

  2. Try to start from this tutorial.

    In the callback function, do a custom_query (or use get_post) for the post and extract only the values that are relevant for you. (I.e: title, excerpt…)

    example shorcode

    [film id=10]
    

    Use id in your function to retrive the content of the film.