Get attachment caption outside of WordPress loop

On my wordpress page, I have the following loop, which successfully outputs an attachment’s caption.

$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>'

Now, I also need to call the attachment caption outside of the loop. This is what I’m trying in functions.php:

function custom_info()
         global $wp_query;
         $query_id = $wp_query->post->ID;
         $attachment_data_query = wp_prepare_attachment_for_js( $query_id );

         wp_register_script( 'custom_data_info');
         $info = array(
             'data_query'   => $attachment_data_query['caption']
         wp_enqueue_script( 'custom_data_info' );
         wp_localize_script('custom_data_info', 'info', $info);
     if ( !is_admin() ) add_action( "wp_enqueue_scripts", "custom_info", 10 );

And then it would be called in the external javascript file like so:

return info.data_query

I know the custom_info function and javascript file are talking with each other correctly. The problem is with how I am defining $query_id

I’m open to any help, thanks!

Read more here: Get attachment caption outside of WordPress loop

Leave a Reply

Your email address will not be published. Required fields are marked *