Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
Get attachment caption outside of Wordpress loop

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

<?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>'
;?>

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

EDIT: Almost fixed. The problem was that I didn't include a foreach statement, and so the first item in the loop was being repeated over and over again.

I've adjusted below, but for some reason, now the array is empty upon output of info.data_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'];

      }
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Are you sure $wp_query will return the correct post ID? In my experience, it's better to use global $post instead. Pass that into wp_prepare_attachment_js() instead:

global $post;
$post_id = $post->ID;
$attachment_data_query = wp_prepare_attachment_for_js( $post_id );
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!