首页 > 解决方案 > 简码 - WordPress

问题描述

我已经为帖子创建了简码,现在我需要在帖子/页面中对帖子进行简码。示例我在 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' );
?>

标签: phpwordpressshortcode

解决方案


通常的做法是递归地“应用”短代码或过滤器。即每次你获得发布内容然后你“do_shortcode”。

在您的函数中,您可以使用“ get_post_field ”来获取帖子 ID 的内容、标题或摘录等。根据您希望输出的呈现方式,您可以使用apply_filtersdo_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"],则“帖子 B”(id 1234”)嵌入在帖子 A 中。如果帖子 B 包含[post_shortcode id=3456 title="Embed 2"],则“帖子 C”(id 3456)也嵌入在帖子 B 和帖子 A 中。


推荐阅读