Eric
Eric

Reputation: 13

Search Wordpress media with Javascript

For testing purposes I want to search through the media of the featured image in Wordpress. But it seems I can't activate the search through a JavaScript action.

The search DOM on the admin page is:

<input type="search" placeholder="Search media..." id="media-search-input" class="search">

I can change the value of the input field with:

// input text string
document.getElementById('media-search-input').value = "test string";

After changing the input value, no search is being done. I guess I have to trigger the search somehow, But I don't know how?

It seems I can't trigger the search with .click(), .focus() or .blur(). There's also no button to hit because WP has a live search functionality.

Upvotes: 0

Views: 322

Answers (2)

haykuro
haykuro

Reputation: 1

Dug around and found this:

wp.media.frames.browse.state().get('library')._requery(true)

Upvotes: 0

epascarello
epascarello

Reputation: 207511

So try to trigger keyboard events (keydown, keyup, keypress)

var elem = document.querySelector("#media-search-input");
var kpEvent = new KeyboardEvent('keydown', { key: 'Enter', keyCode: 13 });
elem.dispatchEvent(kpEvent);

or try input event

var event = new Event('input', {
    bubbles: true,
    cancelable: true,
});

elem.dispatchEvent(event);

Upvotes: 0

Related Questions