Reputation: 369
I have created shortcode for posts, now point is i need to shortcode post in post/page which works. Example i embed post2 in post1 and when i visit post1 i see that post2, but when i embed post1 in page1 i dont see post2
This is code i have written so far.
<?php
function getPostShortcode( $atts, $content = '' ) {
extract( shortcode_atts( array(
'id' => '',
'title' => ''
), $atts, 'post_shortcode' ) );
if ( empty( $atts['id'] ) )
return;
$loop = new WP_Query( array(
'post_type' => 'post',
'p' => $atts['id']
) );
ob_start();
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
$desc = ! empty( $atts['desc'] ) ? $atts['desc'] : get_the_content();
?>
<div class="post-single-shortcode-aka">
<h2><a href="#"><?php echo $title; ?></a></h2>
<p><?php echo $desc; ?></p>
</div>
<?php
endwhile;
wp_reset_postdata();
}
return ob_get_clean();
}
add_shortcode( 'post_shortcode', 'getPostShortcode' );
?>
Upvotes: 1
Views: 99
Reputation: 1399
Normal practice would be to "apply" shortcodes or filters recursively. i.e. each time you get post content then you "do_shortcode".
Within your function you can use"get_post_field" to get the content, or title, or excerpt etc etc for the post ID. Depending on how you want your output rendered you can use either apply_filters or do_shortcode; and there is probably no need for ob buffering.
function getPostShortcode( $atts, $content = '' ) {
extract( shortcode_atts( array(
'id' => '', 'title' => ''
), $atts, 'post_shortcode' ) );
if ( empty( $atts['id'] ) ) return;
// get_post_field can be used to get content, excerpt, title etc etc
$desc = get_post_field('post_content', $atts['id']);
$myEmbed = '<div class="post-single-shortcode-aka"><h2><a href="#">' . $title .'</a></h2><p>';
$myEmbed .= apply_filters('the_content',$desc) . '</p></div>';
// *** OR *** do_shortcode($desc) . '</p></div>';
return $myEmbed;
}
add_shortcode( 'post_shortcode', 'getPostShortcode' );
Edit: added missing </div>
to above code.
I have tested code and: If Post A contains [post_shortcode id=1234 title="Embed 1"]
then "Post B" (id 1234") is embedded in Post A. If Post B contains [post_shortcode id=3456 title="Embed 2"]
then "Post C" (id 3456) is also embedded in BOTH Post B AND Post A.
Upvotes: 2