0

I'm super new to WordPress. Trying to call a Rest API endpoint from WordPress. I can't find an option that runs a piece of code that contacts an external API, in WordPress with a button click.

I have added a button from the widgets pallet but couldn't find an option to call an external piece of code.

I tried finding plugins but had no luck, how do I call an external API hosted on RapidAPI and show the response in a text on button click? and can we call a javascript snippet?

4
  • There is no such option in WordPress. You will need to write your own code. From your theme or a plugin you would need to load JavaScript that adds a click handler to the button. Commented Nov 29, 2022 at 14:01
  • this isn't something you can do with the point and click WP Admin interface or the block editor. You will need to write javascript code and then enqueue it, and write code to listen for when your button is clicked. You should look at the general how do I insert javascript questions on this stack. The most you can do in the editor is give your button an anchor/ID that you can refer to when you write the javascript. Commented Nov 29, 2022 at 14:01
  • Thanks for letting me know. If that's not possible, should one create a button using HTML and use JavaScript or PHP to do a API call? Commented Nov 29, 2022 at 15:30
  • 1
    @JacobPeattie there is an option in WordPress. WPGetAPI is a free plugin for connecting WordPress to APIs including RapidAPI wordpress.org/plugins/wpgetapi Commented Feb 6, 2023 at 10:14

1 Answer 1

1

@TomJNowell pointed you the way to go. You have to enqueue a JS file, and within this JS file you can use any technique to do the REST request, like an XMLHttpRequest object or the fetch API. The REST API itself, of course, is part of WordPress, and defined with register_rest_route(). It is also something you have to provide either within the theme or within a plugin.

Both the JS and the REST API should be part of the same component - i.e. the theme or a plugin.

how do I call an external API hosted on RapidAPI

A web browser does not allow JS functions to invoke a request to another domain name than the originating one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.