【问题标题】:Shortcodes - Wordpress简码 - WordPress
【发布时间】:2018-08-03 08:15:10
【问题描述】:

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

【问题讨论】:

  • 难以理解,您是否测试过在您的 WP 查询之前添加 global $post;。然后请在末尾添加wp_reset_query
  • 我试过了,没用,你
  • 你是说在'page 1'中嵌入'post 1'而不显示'post 1'(因为在你的问题中你说的是'post 2'没有显示)?
  • 您有两篇文章和一页,当我将 post2 的简码放在 post1 中,然后当我将 post1 的简码放在 page1 中时,我看不到 post2,我说的是简码在更多范围内不起作用然后 2 层...
  • 是清楚地显示简码 ( [post_shortcode id=post2] ) 还是什么都没有?

标签: php wordpress shortcode


【解决方案1】:

通常的做法是递归地“应用”短代码或过滤器。即每次你获得发布内容然后你“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' );

编辑:在上面的代码中添加了缺少的&lt;/div&gt;

我已经测试过代码,并且:如果帖子 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 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多