Javascript 获取Wordpress循环外部的附件标题
在我的wordpress页面上,我有以下循环,它成功地输出了附件的标题Javascript 获取Wordpress循环外部的附件标题,javascript,php,wordpress,global-variables,Javascript,Php,Wordpress,Global Variables,在我的wordpress页面上,我有以下循环,它成功地输出了附件的标题 <?php $the_query = new WP_Query(array( 'post_type' => 'attachment')); while ( $the_query->have_posts() ) : $the_query->the_post(); $attachment_data = wp_prepare_attachment_for_js(); echo '<h2>
<?php
$the_query = new WP_Query(array( 'post_type' => 'attachment'));
while ( $the_query->have_posts() ) : $the_query->the_post();
$attachment_data = wp_prepare_attachment_for_js();
echo '<h2>'.$attachment_data['caption'].'</h2>'
;?>
然后在外部javascript文件中调用它,如下所示:
return info.data_query
我知道custom_info函数
和javascript文件之间的对话是正确的。问题在于我如何定义$query\u id
EDIT:几乎修复。问题在于我没有包含foreach
语句,因此循环中的第一项被反复重复
我在下面进行了调整,但由于某些原因,现在在输出info.data\u query
时,数组是空的
function custom_info(){
global $wp_query;
wp_register_script( 'custom_data_info');
$info = array('data_query' => array());
foreach ( $wp_query->posts as $query_id) {
$attachment_data_query = wp_prepare_attachment_for_js( $query_id );
$info['data_query'][$query_id] = $attachment_data_query['caption'];
}
您确定$wp_query将返回正确的帖子ID吗?根据我的经验,最好使用global$post。将其传递到wp_prepare_attachment_js()中:
global $post;
$post_id = $post->ID;
$attachment_data_query = wp_prepare_attachment_for_js( $post_id );
谢谢,我也试过了。它适用于我的搜索和日期页面,但不适用于有特定查询的页面
(例如:$the_query=new WP_query(array(_array_of_things));
接下来,上面的函数在我的搜索和日期页面上工作,但它为所有附件提供了相同的标题(循环中的第一项)。如果有帮助,请编辑上面的内容。
global $post;
$post_id = $post->ID;
$attachment_data_query = wp_prepare_attachment_for_js( $post_id );