Skip to content

Instantly share code, notes, and snippets.

@trepmal
Last active August 12, 2019 14:08
Show Gist options
  • Save trepmal/5417141 to your computer and use it in GitHub Desktop.
Save trepmal/5417141 to your computer and use it in GitHub Desktop.
wp.media.query() works in the console, but not when run like this in a plugin. halp?
<?php
/*
* Plugin Name: wp.media.query
* Plugin URI: trepmal.com
* Description:
* Version: 0
* Author: Kailey Lampert
* Author URI: kaileylampert.com
* License: GPLv2 or later
* TextDomain:
* DomainPath:
* Network:
*/
$wpmediaquery_test = new wpmediaquery_test();
class wpmediaquery_test {
function __construct() {
add_action( 'add_meta_boxes', array( &$this, 'add_meta_boxes' ) );
}
function add_meta_boxes() {
add_meta_box( 'wpmediaquery-test', 'wp.media.query test', array( &$this, 'add_meta_box' ), 'page', 'normal', 'low');
}
function add_meta_box( $post ) {
echo 'lorem';
add_action('admin_print_footer_scripts', array( &$this, 'js' ), 99 );
}
function js() {
?><script>
jQuery(document).ready(function($){
var query = wp.media.query(); // { post__in: [1709] }
query.more();
result = query.length;
console.log( 'query length', result ); // 0
var singleimage = wp.media.model.Attachment.get( 7 ); // where 7 is the id of a single attachment
singleimage.fetch();
result = singleimage.toJSON();
console.log( 'single img object', result ); // { id: 7 }
});
</script><?php
}
}
@funkatron82
Copy link

Thank you @bradyvercher, that answer helped me a lot.

@socialblogsite
Copy link

Can you post the answer?
I also want to query images from the DB and I get an empty object in the console (I'm not that good to know how to use it, and chrome has fooled me before by showing me output in the console different than what JS retrieves)
Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment