2015-01-12 3 views
0

У меня есть небольшая проблема в моем Shortcode, который я создаю для WordPress. Цикл foreach не отображает несколько сообщений каждый раз. Я не уверен, почему он это делает, потому что если я var_dump переменная $post, это показывает, что оба сообщения доступны этой переменной, может кто-то помочь мне, пожалуйста?Foreach не отображает несколько содержимого

КОД:

function notes_shortcode($atts) { 
global $post; 

$atts = shortcode_atts(array('category' => $args["category"]), $atts, 'notes'); 
$args = array('category_name' => $atts["category"]); 
$posts = get_posts($args); 
$date = get_the_date('d', $post->ID); 
$month = get_the_date('M', $post->ID); 

    foreach($posts as $post) { 
     setup_postdata($post); 
     $imgURL = getpostImage($post->ID); 
     $title = get_the_title($post->ID); 
     $content = substr(get_the_content() , 0, 125); 
     $post = '<div class="animated fadeInUp" data-animation="fadeInUp" data-delay="200" style="opacity: 0;">'; 
     $post .= '<div class="col-md-4 bloglist">'; 
     $post .= '<div class="post-content">'; 
     $post .= '<div class="post-image">'; 
     $post .= '<div class="flexslider blog-slider">'; 
     $post .= '<div class="overlay" style="opacity: 0;"></div>'; 
     $post .= '<div class="flex-viewport" style="overflow: hidden; position: relative;">'; 
     $post .= '<ul class="slides" style="width: 800%; -webkit-transition: 0s; transition: 0s; -webkit-transform: translate3d(-350px, 0px, 0px);">'; 
     $post .= '<li class="clone" aria-hidden="true" style="width: 350px; float: left; display: block;"> <img src="' . $imgURL . '" alt="" draggable="false"> </li>'; 
     $post .= '<li class="flex-active-slide" style="width: 350px; float: left; display: block;"> <img src="' . $imgURL . '" alt="" draggable="false"> </li>'; 
     $post .= '<li style="width: 350px; float: left; display: block;"> <img src="' . $imgURL . '" alt="" draggable="false"> </li>'; 
     $post .= '<li class="clone" aria-hidden="true" style="width: 350px; float: left; display: block;"> <img src="' . $imgURL . '" alt="" draggable="false"></li>'; 
     $post .= '</ul></div></div></div>'; 
     $post .= '<div class="date-box"><span class="day">' . $date . '</span>'; 
     $post .= '<span class="month">' . $month . '</span> </div>'; 
     $post .= '<div class="post-text">'; 
     $post .= '<h3><a href="css/#">' . $title . '</a></h3>'; 
     $post .= '<p> ' . $content . '<br>'; 
     $post .= ' <a href="#" class="btn-text">Read More</a></p></div></div></div></div>'; 
     return $post; 
    } 
} 
add_shortcode('notes', 'notes_shortcode'); 

function getpostImage($postid) { 
    if (has_post_thumbnail($post->ID)){ 
      $imgArray = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'thumbnail'); 
      $imgURL = $imgArray[0]; 
      return $imgURL; 
    } 
} 

Спасибо ..

ответ

1

Хорошо, я решил эту проблему. Я использовал фильтры WordPress для привязки переменной $buff и возвращал ее за пределы цикла, ниже это решение, если кому-то это нужно.

function notes_shortcode($atts) { 
global $post; 
global $buf; 

$atts = shortcode_atts(array('category' => $args["category"], 'posts_per_page' => $args["posts_per_page"]), $atts, 'notes'); 
$args = array('category_name' => $atts["category"], 'posts_per_page' => $atts["posts_per_page"]); 
$posts = get_posts($args); 
$date = get_the_date('d', $post->ID); 
$month = get_the_date('M', $post->ID); 
$buf = ''; 
$postHolder = array(); 

foreach($posts as $post) { 
     setup_postdata($post); 
     $imgURL = getpostImage($post->ID); 
     $title = get_the_title($post->ID); 
     $content = substr(get_the_content() , 0, 125); 

     $buf .= '<div class="animated fadeInUp" data-animation="fadeInUp" data-delay="200" style="opacity: 0;">'; 
     $buf .= '<div class="col-md-4 bloglist">'; 
     $buf .= '<div class="post-content">'; 
     $buf .= '<div class="post-image">'; 
     $buf .= '<div class="flexslider blog-slider">'; 
     $buf .= '<div class="overlay" style="opacity: 0;"></div>'; 
     $buf .= '<div class="flex-viewport" style="overflow: hidden; position: relative; max-width: 350px; max-height: 175px; padding-bottom: 15px; margin-bottom: 15px;">'; 
     $buf .= '<ul class="slides" style="width: 800%; -webkit-transition: 0s; transition: 0s; -webkit-transform: translate3d(-350px, 0px, 0px);">'; 
     $buf .= '<li class="clone" aria-hidden="true" style="width: 350px; float: left; display: block;"> <img src="' . $imgURL . '" alt="" draggable="false"> </li>'; 
     $buf .= '<li class="flex-active-slide" style="width: 350px; float: left; display: block;"> <img src="' . $imgURL . '" alt="" draggable="false"> </li>'; 
     $buf .= '<li style="width: 350px; float: left; display: block;"> <img src="' . $imgURL . '" alt="" draggable="false"> </li>'; 
     $buf .= '<li class="clone" aria-hidden="true" style="width: 350px; float: left; display: block;"> <img src="' . $imgURL . '" alt="" draggable="false"></li>'; 
     $buf .= '</ul></div></div></div>'; 
     $buf .= '<div class="date-box"><span class="day">' . $date . '</span>'; 
     $buf .= '<span class="month">' . $month . '</span> </div>'; 
     $buf .= '<div class="post-text">'; 
     $buf .= '<h3><a href="css/#">' . $title . '</a></h3>'; 
     $buf .= '<p> ' . $content . '<br>'; 
     $buf .= ' <a href="#" class="btn-text">Read More</a></p></div></div></div>'; 
     $buf .= apply_filters('post_class', '</div>', $atts); 
    } 
    $buf .= apply_filters('post_class', '', $atts); 
    return $buf; 
} 

add_shortcode('notes', 'notes_shortcode'); 

function getpostImage($postid) { 
    if (has_post_thumbnail($post->ID)){ 
      $imgArray = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'thumbnail'); 
      $imgURL = $imgArray[0]; 
      return $imgURL; 
    } 
} 

Thankyou все за помощь ..

+0

Просто примечание: зачем использовать глобальную функцию сверху? вы не используете (по крайней мере, я надеюсь) гладко объявленный var, поэтому строки thoose здесь бесполезны. [См. Это] (http://php.net/manual/en/language.variables.scope.php) для подробной информации об использовании глобального для изменения области. (вы являетесь функцией getpostid в другой руке, используйте '$ post-> id' вместо аргумента функции, является ли это намеренным (я подозреваю, что он работает из-за глобального, но звучит как ошибка))? – Tensibai

0

Вы возвращаете функцию, это означает, что ваши делают конец функции. Что вы можете сделать, это отправить массив, а затем цикл его later.Use кода ниже

function notes_shortcode($atts) { 
global $post; 

$atts = shortcode_atts(array('category' => $args["category"]), $atts, 'notes'); 
$args = array('category_name' => $atts["category"]); 
$posts = get_posts($args); 
$date = get_the_date('d', $post->ID); 
$month = get_the_date('M', $post->ID); 
$array = array(); 
    foreach($posts as $post) { 
     setup_postdata($post); 
     $imgURL = getpostImage($post->ID); 
     $title = get_the_title($post->ID); 
     $content = substr(get_the_content() , 0, 125); 
     $post = '<div class="animated fadeInUp" data-animation="fadeInUp" data-delay="200" style="opacity: 0;">'; 
     $post .= '<div class="col-md-4 bloglist">'; 
     $post .= '<div class="post-content">'; 
     $post .= '<div class="post-image">'; 
     $post .= '<div class="flexslider blog-slider">'; 
     $post .= '<div class="overlay" style="opacity: 0;"></div>'; 
     $post .= '<div class="flex-viewport" style="overflow: hidden; position: relative;">'; 
     $post .= '<ul class="slides" style="width: 800%; -webkit-transition: 0s; transition: 0s; -webkit-transform: translate3d(-350px, 0px, 0px);">'; 
     $post .= '<li class="clone" aria-hidden="true" style="width: 350px; float: left; display: block;"> <img src="' . $imgURL . '" alt="" draggable="false"> </li>'; 
     $post .= '<li class="flex-active-slide" style="width: 350px; float: left; display: block;"> <img src="' . $imgURL . '" alt="" draggable="false"> </li>'; 
     $post .= '<li style="width: 350px; float: left; display: block;"> <img src="' . $imgURL . '" alt="" draggable="false"> </li>'; 
     $post .= '<li class="clone" aria-hidden="true" style="width: 350px; float: left; display: block;"> <img src="' . $imgURL . '" alt="" draggable="false"></li>'; 
     $post .= '</ul></div></div></div>'; 
     $post .= '<div class="date-box"><span class="day">' . $date . '</span>'; 
     $post .= '<span class="month">' . $month . '</span> </div>'; 
     $post .= '<div class="post-text">'; 
     $post .= '<h3><a href="css/#">' . $title . '</a></h3>'; 
     $post .= '<p> ' . $content . '<br>'; 
     $post .= ' <a href="#" class="btn-text">Read More</a></p></div></div></div></div>'; 
     $array[] = $post; 
    } 
return $array; 
} 
add_shortcode('notes', 'notes_shortcode'); 

function getpostImage($postid) { 
    if (has_post_thumbnail($post->ID)){ 
      $imgArray = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'thumbnail'); 
      $imgURL = $imgArray[0]; 
      return $imgURL; 
    } 
} 

Надеется, что это помогает вам

+0

Я думаю, что это должно работать, но так или иначе, его нет. Я не знаю, почему, он выводит меня на «Массив». Я думаю, что в коде есть простая ошибка. –

+0

.. и рядом с этим вы пытаетесь изменить данные WITHIN foreach. Это невозможно без использования либо другой вспомогательной переменной, либо 2. обновления переменной $ post по ссылке. Обратите внимание: «Чтобы иметь возможность напрямую изменять элементы массива в цикле, перед значением $ value следует &. В этом случае значение будет присвоено ссылкой.» См. Здесь: http://php.net/manual/en/ control-structures.foreach.php – despina

+0

Downvoting из-за возврата массива и использования итератора в качестве новой переменной внутри цикла (измените его и добавьте array_join по крайней мере, но это бесполезно здесь, лучше посмотрите на сам ответ @FahadSohail). – Tensibai

Смежные вопросы