Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/434.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取Wordpress循环外部的附件标题_Javascript_Php_Wordpress_Global Variables - Fatal编程技术网

Javascript 获取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>

在我的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>'.$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 );