自定义短代码不会显示在 WordPress 中的正确位置

问题描述 投票:0回答:1

我有一个自定义帖子类型(组合),并且我创建了一个自定义短代码来显示此自定义帖子类型的最新帖子。它可以工作,但是它不会显示在正确的位置。它位于页面顶部,而不是我发布的短代码的底部。任何帮助都会很棒!

<?php
function portfolio_posts(){?>
    <?php
    $args = array(
      'numberposts' => '8',
      'post_type'    => 'portfolio'
     );
    ?>
    <?php
    // the query.
    $the_query = new WP_Query( $args ); ?>

    <?php if ( $the_query->have_posts() ) : ?>
        <!-- pagination here -->

        <!-- the loop -->
        <?php
        while ( $the_query->have_posts() ) :
            $the_query->the_post();
            ?>
        <!-- Thumnail, Title and View More Button -->
        <p> <?php the_post_thumbnail('full', array('class' => 'img-fluid')); ?></p>
        <h2 class="post-title"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
        <a class="btn" href="<?php the_permalink(); ?>">View</a>
        <?php endwhile; ?>
        <!-- end of the loop -->

        <!-- pagination here -->

        <?php wp_reset_postdata(); ?>

    <?php else : ?>
        <p><?php esc_html_e( 'Sorry, no posts matched your criteria.' ); ?></p>
    <?php endif; ?>


<?php    }
add_shortcode('latest_projects', 'portfolio_posts');

一切正常,只是我无法让它显示在正确的位置。

php wordpress shortcode custom-wordpress-pages custom-theme
1个回答
0
投票

WordPress 中的短代码需要返回内容而不是回显,您可以像这样使用

ob_start
ob_get_clean

<?php
function portfolio_posts(){
    ob_start();
    $args = array(
      'numberposts' => '8',
      'post_type'    => 'portfolio'
     );
    // the query.
    $the_query = new WP_Query( $args );

    if ( $the_query->have_posts() ) : ?>
        <!-- pagination here -->

        <!-- the loop -->
        <?php
        while ( $the_query->have_posts() ) :
            $the_query->the_post();
            ?>
        <!-- Thumnail, Title and View More Button -->
        <p> <?php the_post_thumbnail('full', array('class' => 'img-fluid')); ?></p>
        <h2 class="post-title"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
        <a class="btn" href="<?php the_permalink(); ?>">View</a>
        <?php endwhile; ?>
        <!-- end of the loop -->

        <!-- pagination here -->

        <?php wp_reset_postdata();

    else : ?>
        <p><?php esc_html_e( 'Sorry, no posts matched your criteria.' ); ?></p>
    <?php endif;

    return ob_get_clean();
}
add_shortcode('latest_projects', 'portfolio_posts');
© www.soinside.com 2019 - 2024. All rights reserved.