How to retrieve image only from wordpress rest api using Javscript

Viewed 13

I am making a blog, using wordpress rest API to fetch the blog posts. In the wordpress post, I have som lorem ipsum text, and an image beneath. I want to later implement code that lets the user click on the image and displays it in modal(makes it larger).

I have a featured image which is easy enough to display. However, when trying to fetch the content of the post, both the text content and the image is displayed together. I would rather be able to retrieve and display the text on its own line, and the image on another, so that I can easier select and style it later.

This is the code so far:

const queryString = document.location.search;
const params = new URLSearchParams(queryString);
const queryID = params.get("id");

const loadSpecificPost = async (url) => {
    const response = await fetch(url);
    const post = await response.json(url);

    for (let i = 0; i < post.length; i++){
        const featuredImage = post[i]._embedded["wp:featuredmedia"][0]["source_url"]
        
        if (post[i].id == queryID){
            main.innerHTML = ` 
                                <section class="pageTitle">
                                    <h1>${post[i].title.rendered}</h1>
                                </section>
                                <div>
                                    ${post[i].excerpt.rendered}
                                <img src="${featuredImage}" class="featuredImage">
                                    </div>
                                <div class="bodyText">
                                    ${post[i].content.rendered}
                                </div>
                                `;
                                console.log(post[i].content)
        }
    }
}

loadSpecificPost(url);

This way, I have no way of selecting the image (or the text content for that mattter) on its own, and I cant think of or find a different way to do it. Hope someone can help.

0 Answers
Related