2013-10-10 2 views
0

У меня есть массив ссылок, который я использую для отображения списка статей. Каждая из ссылок вводится в текстовое поле при создании сообщения.Петля показывает только последний элемент

Последний элемент массива отображается правильно, в то время как первые три вытягивают текущее название страницы для заголовка статьи и текущего пользователя, зарегистрированного в качестве автора. И заголовок, и автор неверны.

Любые идеи?

$ URLs Массив

Array ( 
    [0] => http://localhost:8888/2013/10/custom-toothbrush-six-second-cleaning.html 
    [1] => http://localhost:8888/2013/10/climate-change-global-warming-al-gore.html 
    [2] => http://localhost:8888/2013/10/custom-toothbrush-six-second-cleaning.html 
    [3] => http://localhost:8888/2013/10/climate-change-global-warming-al-gore.html 
    ) 

Вот код PHP

$urls=explode(PHP_EOL, get_field('publishing_articles')); 
foreach($urls as $url){  
    $id=url_to_postid($url); 
    $the_title=get_the_title($id); 
    $author_id=get_post_field('post_author',$id); 
    $author_displayname=get_the_author_meta('display_name',$author_id); 
    $author_nicename=get_the_author_meta('user_nicename',$author_id); 

    echo '<li>'.$id; 
    echo '<a href="/author/'.$author_nicename.'" title="'.$the_title.'"><img width="50" src="/wp-content/uploads/authors/'.$author_id.'.jpg" alt="'.$author_displayname.'"/></a>'; 
    echo '<a href="'.$url.'" title="'.$the_title.'">'.$the_title.'</a>'; 
    echo '</li>'; 
} 

И HTML Output

<li>0<a href="/author/admin" title="The Future Of Light"><img width="50" src="/wp-content/uploads/authors/362.jpg" alt="admin"/></a><a href="http://localhost:8888/2013/10/custom-toothbrush-six-second-cleaning.html" title="The Future Of Light">The Future Of Light</a></li> 
<li>0<a href="/author/admin" title="The Future Of Light"><img width="50" src="/wp-content/uploads/authors/362.jpg" alt="admin"/></a><a href="http://localhost:8888/2013/10/climate-change-global-warming-al-gore.html" title="The Future Of Light">The Future Of Light</a></li> 
<li>0<a href="/author/admin" title="The Future Of Light"><img width="50" src="/wp-content/uploads/authors/362.jpg" alt="admin"/></a><a href="http://localhost:8888/2013/10/custom-toothbrush-six-second-cleaning.html" title="The Future Of Light">The Future Of Light</a></li> 
<li>210664<a href="/author/daniela-walker" title="How Al Gore Is Making Global Warming Personal"><img width="50" src="/wp-content/uploads/authors/384.jpg" alt="Daniela Walker"/></a><a href="http://localhost:8888/2013/10/climate-change-global-warming-al-gore.html" title="How Al Gore Is Making Global Warming Personal">How Al Gore Is Making Global Warming Personal</a></li> 
+0

Можете ли вы опубликовать то, что выводимый HTML выглядит как –

+0

Правильно ли отображается '$ id' в каждом случае? – Hobo

+0

Добавлен HTML-вывод – ok1ha

ответ

0

Кажется, проблема была куда менее привлекательной, чем я думал. Я не обрезал строки, которые строят массив $ id. Кроме того, я исправил функции автора по предложениям геомага.

$urls=explode(PHP_EOL, get_field('publishing_articles')); 

foreach($urls as $url){  

    $id=url_to_postid(trim($url)); 

    $the_title=get_the_title($id); 
    $author_id=get_post_field('post_author',$id); 
    $author_url=get_the_author_meta('user_nicename',$author_id); 
    $author_name=get_the_author_meta('display_name',$author_id); 

    $output.='<li>'; 
    $output.='<a class="author" href="/author/'.$author_url.'" title="More Articles By '.$author_name.'"><img src="/wp-content/uploads/authors/'.$author_id.'.jpg" alt="'.$author_name.'" onerror="author_img_error(this);" /></a>'; 
    $output.='<a class="link" href="'.$url.'" title="'.$the_title.'">'.$the_title.'</a>'; 
    $output.='</li>'; 
} 
echo $output; 
1

Прежде всего, get_the_author_meta() возвращает мета о текущей, logged- в пользователе, если идентификатор пользователя не указан. Это означает, что вы используете параметр NULL$author_id. get_the_title() имеет аналогичное поведение в отношении текущего сообщения соответственно. Это означает, что $id тоже NULL.

Это может означать, что url_to_postid() возвращает NULL id.

Вышеуказанное в свою очередь означает, что $urls не инициализирован, как ожидалось.

И get_field() является причиной этого. Как и все вызовы API ACF, его необходимо называть после init (т.е. в обработчике действий).

См. Также: this.

+0

Спасибо за всю помощь, но я все еще полностью запутался, вызвав что-то после init ... Я попробовал add_action ('wp_head', 'get_field'); но это ничего не изменило. – ok1ha

+1

Событие 'wp_head' запускается после' init', да. [Вот ссылка на последовательность действий во время типичного запроса] (http://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request).Но я не имел в виду, что вы должны называть 'get_fied()' самостоятельно, но, скорее, всю вашу процедуру (включая вызов 'get_field()') _ то есть код, который вы опубликовали. – geomagas

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