Php 短代码-Wordpress

Php 短代码-Wordpress,php,wordpress,shortcode,Php,Wordpress,Shortcode,我已经为帖子创建了快捷编码,现在的重点是我需要在帖子/页面中对帖子进行快捷编码。例如,我在post1中嵌入post2,当我访问post1时,我看到post2,但当我在page1中嵌入post1时,我看不到post2 这是我到目前为止写的代码 <?php function getPostShortcode( $atts, $content = '' ) { extract( shortcode_atts( array( 'id' => '

我已经为帖子创建了快捷编码,现在的重点是我需要在帖子/页面中对帖子进行快捷编码。例如,我在post1中嵌入post2,当我访问post1时,我看到post2,但当我在page1中嵌入post1时,我看不到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' );
?>


通常的做法是递归地“应用”短代码或过滤器。i、 e.每次当你收到帖子内容时,你都会“做短码”

在您的函数中,您可以使用“get_post_field”获取文章ID的内容、标题或摘录等。根据您希望输出的呈现方式,您可以使用apply_筛选器或do_快捷码;而且可能不需要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' );
函数getPostShortcode($atts,$content=''){ 提取(短码)附件(数组)( 'id'=>'','title'=>' ),$atts,'post_shortcode'); 如果(空($atts['id'])返回; //get_post_字段可用于获取内容、摘录、标题等 $desc=get_post_字段('post_content',$atts['id']); $myEmbed=“”; $myEmbed.=apply_filters('the_content',$desc)。“

”; //***或***使用短码($desc)。“

”; 返回$myEmbed; } 添加_-shortcode('post_-shortcode','getPostShortcode'); 编辑:将缺少的
添加到上述代码中


我已经测试了代码,并且:如果帖子A包含
[Post\u shortcode id=1234 title=“Embed 1”]
,那么“Post B”(id 1234)就嵌入到帖子A中。如果帖子B包含
[Post\u shortcode id=3456 title=“Embed 2”]
那么“Post C”(id 3456)也嵌入了B帖和A帖。

很难理解,您是否测试过在WP查询之前添加
global$Post;
。请在末尾添加
WP\u reset\u Query
。我已经尝试过了,但没有帮助,您是说在“第1页”中嵌入“Post 1”而不是显示“Post 1”(因为在你的问题中,你说的是‘post2’没有显示)?你有两篇文章和一页,当我在post1中放置post2的短码,然后当我在page1中放置post1的短码时,我没有看到post2,我说的是短码在超过2层中不起作用……它是否清楚地显示了短码([post_shortcode id=post2])还是什么都没有?