#php #wordpress
#php #wordpress
Вопрос:
Я новичок в разработке 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' );
Мой вопрос был бы таков: как я могу поместить цикл внутри моего короткого кода?
Ответ №1:
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;
}
Ответ №2:
<?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; ?>