Last active
April 16, 2019 18:08
-
-
Save alexmustin/2f1b48d99a9b5b34b3ffb1249a4ac575 to your computer and use it in GitHub Desktop.
Simple Shortcode to display a Featured Page or Post
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * This code adds a custom Shortcode to display a "Featured Post." | |
| */ | |
| function featuredpost_shortcode( $atts ) { | |
| // Var defaults | |
| $defaults['id'] = 1; | |
| $postID = ''; | |
| $postTypesArray = array('post', 'page'); // add more post types here | |
| // Get Attributes from the Shortcode | |
| $scAtts = shortcode_atts( $defaults, $atts, 'theme_textdomain' ); | |
| // If user has not provided an ID, exit | |
| if ( empty( $scAtts['id'] ) ) { | |
| return 'Please provide a Post ID.'; | |
| } | |
| // Assign postID var | |
| $postID = (int)$scAtts['id']; | |
| // Create arguments for Query | |
| $args = array( | |
| 'p' => $postID, | |
| 'post_type' => $postTypesArray | |
| ); | |
| // The Query | |
| $the_query = new WP_Query( $args ); | |
| ob_start(); | |
| if ( $the_query->have_posts() ) { | |
| while ( $the_query->have_posts() ) { | |
| $the_query->the_post(); | |
| // Get the featured post content | |
| $content = get_post_field( 'post_content', get_the_ID() ); | |
| // Get content parts | |
| $content_parts = get_extended( $content ); | |
| // Get all content before <!--more--> tag | |
| $real_excerpt = $content_parts['main']; | |
| // Display the Featured Post | |
| echo '<section class="featured-post widget featured-content post-' . get_the_ID() . ' type-' . get_post_type() . '">'; | |
| echo '<div class="widget-wrap">'; | |
| echo '<article class="entry">'; | |
| echo '<div class="stripe"></div>'; | |
| echo '<div class="wrapper">'; | |
| echo '<a href="' . get_the_permalink() . '">' . get_the_post_thumbnail() . '</a>'; | |
| echo '<header class="entry-header"><h4 class="entry-title" itemprop="headline"><a href="' . get_the_permalink() . '">' . get_the_title() . '</a></h4></header>'; | |
| echo '<div class="entry-content">' . $real_excerpt . '<br><a href="' . get_the_permalink() . '" class="more-link">Learn More</a></div>'; | |
| echo '</div>'; | |
| echo '</article>'; | |
| echo '</div>'; | |
| echo '</section>'; | |
| } | |
| } else { | |
| echo "Nothing found. Please check the Post ID and try again."; | |
| } | |
| $output = ob_get_contents(); | |
| ob_end_clean(); | |
| /* Restore original Post Data */ | |
| wp_reset_postdata(); | |
| return $output; | |
| } | |
| add_shortcode( 'featured-post', 'featuredpost_shortcode' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment