如何为我的WP_Query循环创建一个短代码?

时间:2016-10-18 22:26:32

标签: php wordpress

我是一个菜鸟开发人员,我刚刚使用高级自定义字段创建了我的第一个自定义模板页面并设法循环。

        <?php 
            $args = array(
                'post_type' => 'art',
                'orderby' => 'title',
                'order' => 'ASC'
            );
            $the_query = new WP_Query( $args );         
        ?>
        <?php if ( have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?> 

        <?php get_template_part( 'content', 'art' ); ?>

        <?php endwhile; endif; ?>

但我不仅要在模板页面内使用它,还要在我想要的任何地方使用它。因此我需要创建一个短代码。

示例:

function foobar_func( $atts ){
    return "foo and bar";
}
add_shortcode( 'foobar', 'foobar_func' );

我的问题是:如何将循环放在我的短代码中?

2 个答案:

答案 0 :(得分:0)

add_shortcode( 'foobar', 'foobar_func' );
function foobar_func( $atts ) {
global $post;
$output = '';
$args = array(
            'post_type' => 'art',
            'orderby' => 'title',
            'order' => 'ASC',
            'posts_per_page' => 10,

);
$fe_query= new WP_Query( $args );
if ( $fe_query->have_posts() ) {
    $output .= '<ul class="fe-query-results-shortcode-output">';
    while ( $fe_query->have_posts() ) {
        $fe_query->the_post();

        $title = get_the_title();
        $link = get_the_permalink();

        $output .= "<li><a href=\"{$link}\">{$title}</a></li>";
       }
       $output .= '</ul>';
      } else {
     $output .= '<div class="fe-query-results-shortcode-output-none">No      results were found</div>';
    }

wp_reset_postdata();
return $output;
}

答案 1 :(得分:0)

<?php
function loop_art() {
       ob_start();
       get_template_part('loop_art');
       return ob_get_clean();   
    } 
    add_shortcode( 'loop_art', 'loop_art' );
?>

<?php 
                $args = array(
                    'post_type' => 'art',
                    'orderby' => 'title',
                    'order' => 'ASC'
                );
                $the_query = new WP_Query( $args );         

            if ($the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post()
                   ?>   

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    <header class="entry-header">

        <h1 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>

        <div class="entry-meta">
            <p>Price: $<?php the_field('price'); ?></p>
        </div><!-- .entry-meta -->

    </header><!-- .entry-header -->

    <div class="entry-content">

        <p><img src="<?php the_field('image'); ?>" alt="Example image of <?php the_title(); ?>"></p>


    </div><!-- .entry-content -->   

</article>

              <?php endwhile; endif; ?>