从函数返回字符串
问题描述:
所以我在functions.php中有一个函数,我想在我的wordpress网站的其他部分用shortcode调用它,但问题是我不知道如何将函数的结果保存到一个变量。如果有人能帮助我,我将非常感激。这是php代码:从函数返回字符串
<?php
function get_slider() {
$args = array(
'post_type' => 'something',
);
$posts = get_posts($args);
echo $posts;
if($posts): ?>
<div class="custom-posts-grid">
<?php foreach($posts as $post): setup_postdata($post); ?>
<?php if(have_rows('poslovna_darila')): ?>
<?php while(have_rows('poslovna_darila')): the_row(); ?>
<div class="slider_slick">
<?php // vars
$image = get_sub_field('thumbnail_for_poslovna_darila');
$link = get_sub_field('url_poslovna_darila');
$count = count($posts);
?>
<div class="slide">
<a href="<?php echo $link; ?>">
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt'] ?>" class="image-overlay-post" />
</a>
</div>
</div>
<?php endwhile; ?>
<?php endif; ?>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php endif;
}
add_shortcode ('slick_slider' , 'get_slider'); ?>
该代码返回数组,但我需要从中获得一个值,或者如果可能的话滑块。
答
您可以使用输出缓冲区来返回短代码中的字符串。
<?php
function get_slider() {
$args = array(
'post_type' => 'something',
);
$posts = get_posts($args);
//echo $posts;
ob_start(); // start the output buffer
if ($posts) : ?>
<div class="custom-posts-grid">
<?php foreach ($posts as $post) : setup_postdata($post); ?>
<?php if (have_rows('poslovna_darila')): ?>
<?php while (have_rows('poslovna_darila')) : the_row(); ?>
<div class="slider_slick">
<?php // vars
$image = get_sub_field('thumbnail_for_poslovna_darila');
$link = get_sub_field('url_poslovna_darila');
$count = count($posts);
?>
<div class="slide">
<a href="<?php echo $link; ?>">
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt'] ?>" class="image-overlay-post" />
</a>
</div>
</div>
<?php endwhile; ?>
<?php endif; ?>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
</div>
<?php endif;
// return the contents of the output buffer as a string
return ob_get_clean();
}
add_shortcode('slick_slider' , 'get_slider'); ?>
返回array = for for循环! – xYuri