WordPress.org

Ready to get started?Download WordPress

Forums

Adding an excerpt to a page with shortcode (2 posts)

  1. JMengMO
    Member
    Posted 2 years ago #

    I am creating a web site with WordPress 3.2 and a very slightly modified version of the twentyten theme. The site has a home page, about us, contact, and a few other pages. All of my pages are set up as single column - not the default two column layout.

    On one of the pages, I would like to display a post excerpt. I have the page laid out exactly as I want it, and in the place that I want the excerpt to display, I have hard coded the excerpt text. What I am hoping for is a way to replace the hard coded excerpt text with a shortcode that would insert the actual excerpt text.

    So if the excerpt for post #100 is "This is the text for post 100", I would like to insert something like [insert-excerpt id=100], and "This is the text for post 100" on the page.

    I honestly thought this would be trivial, but after searching all morning, I have not found anything that does what I just described. Can anyone point me in the right direction?

  2. MichaelH
    Member
    Posted 2 years ago #

    Something like this in your theme functions.php

    function mh_display_excerpt_shortcode( $atts ) {
      extract(shortcode_atts(array(
        'excerptid' => ''
      ), $atts));
      if ($excerptid) {
        $args=array(
        'p' => $excerptid,
        'post_type' => 'post',
        'post_status' => 'publish'
      );
        $my_query = new WP_Query($args);
        if ($my_query) {
          echo apply_filters( 'the_excerpt', $my_query->posts[0]->post_excerpt );
        }
      }
      return;
    }
    add_shortcode('display_excerpt', 'mh_display_excerpt_shortcode');

    Then use this for your post content

    [display_excerpt excerptid="100"]

Topic Closed

This topic has been closed to new replies.

About this Topic