Skip Navigation

[Resolved] Search and get the post IDs of the first 5 results

This thread is resolved. Here is a description of the problem and solution.

Problem: I'm using a 3rd-party JavaScript plugin that requires access to the IDs of the first 5 results in a custom search View. How can I access the result post IDs in JavaScript?

Solution: Add the post ID to the markup of each item in the Loop as a data attribute, then use jQuery.each() to loop over the results and obtain that information. Trigger this code on document ready for non-AJAX Views, or use the Frontend Events button to trigger it on pagination and search events.

Relevant Documentation:
@https://api.jquery.com/jquery.each/

This support ticket is created 6 years, 6 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 - -
13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 - -

Supporter timezone: America/New_York (GMT-04:00)

This topic contains 2 replies, has 2 voices.

Last updated by Nicholas 6 years, 6 months ago.

Assisted by: Christian Cox.

Author
Posts
#957981

Hello,
I'd like to click on search and then pick up the post IDs of the first 5 results and then pass them on into the dataLayer.
hidden link

Do you have any IDea how I could do that? 😉 How would I get the IDs of the result(s)?

Regards,
Nick

#958347

I have an IDea!

I assume you're using a custom search View of some kind to search and get results. If the View updates with AJAX, you can use the Frontend Events button in the Search and Pagination JS editor panel to build event listeners with jQuery. One of those event listeners will help you trigger custom JavaScript when custom search results have been updated. Then in that event listener callback, you could loop over the current results using jQuery.each(). If you add the post ID as a data attribute or something in the Loop Output, you could get that information in the .each loop and build an array of data to push onto the datalayer. You'll have access to the loop index in the .each callback, and you can stop pushing data after index 4.
http://api.jquery.com/jquery.each/

It's not as clean as a pure JS API, but it's the best I can think of right now. If the View does not use AJAX updates, then you can just trigger the same code on jQuery(document).ready() to loop over the results and push them onto the datalayer.

#958772

Thank you, Christian. This is very good advice.