[英]Shortcodes - Wordpress
我已经为帖子创建了简码,现在要指出的是我需要对帖子/页面中的帖子进行简码。 示例我将post2嵌入post1,当我访问post1时我看到了post2,但是当我将post1嵌入page1时我没有看到post2
这是我到目前为止编写的代码。
<?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' );
?>
通常的做法是递归“应用”短代码或过滤器。 即, 每次您获得帖子内容,那么您就可以“ do_shortcode”。
在您的函数中,您可以使用“ get_post_field ”来获取帖子ID的内容,标题或摘要等。 根据您希望输出的呈现方式,可以使用apply_filters或do_shortcode ; 并且可能不需要ob缓冲。
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' );
编辑:在上面的代码中添加了缺少的</div>
。
我已经测试了代码,并且:如果帖子A包含[post_shortcode id=1234 title="Embed 1"]
则在帖子A中嵌入了“帖子B”(id 1234“)。如果帖子B包含[post_shortcode id=3456 title="Embed 2"]
然后“帖子C”(编号3456)也将同时嵌入到帖子B和帖子A中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.