WordPress.org

Ready to get started?Download WordPress

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/wp prepare attachment for js

Description

Prepares an attachment post object for JS, where it is expected to be JSON-encoded and fit into an Attachment model.

Usage

 <?php wp_prepare_attachment_for_js$attachment ?> 

Parameters

$attachment
(mixed) (required) Attachment ID or object.
Default: None

Return Value

(array) 
Array of attachment details.

The fields returned are:

  • id
  • title
  • filename
  • url
  • link
  • alt
  • author
  • description
  • caption
  • name
  • status
  • uploadedTo
  • date
  • modified
  • menuOrder
  • mime
  • type
  • subtype
  • icon
  • dateFormatted
  • nonces
  • editLink
  • sizes
  • width
  • height
  • fileLength
  • compat

Examples

Pass image data to a js gallery.

<?php
add_action( 'wp_head', 'my_js_gallery_add_gallery_images', 1 );
function my_js_gallery_add_gallery_images(){
	global $post;

	$gallery_images = array();
	$attachments = get_posts( array(
		'post_type' => 'attachment',
		'post_status' => 'inherit',
		'post_parent' => $post->ID,
		'post_mime_type' => 'image',
	) );

	foreach( $attachments as $attachment )
		$gallery_images[] = wp_prepare_attachment_for_js( $attachment->ID );

	wp_localize_script( 'my-js-gallery', 'my_js_gallery', array(
		'images' => $gallery_images,
	) );
}

Default Usage

Change Log

Source File

wp_prepare_attachment_for_js() is located in wp-includes/media.php.

Related