germanyague
germanyague

Reputation: 3

How do I extract a image from a Wordpress post and put it in a php code

I'm making a webpage inside of which there's a Wordpress working serving news.

I want the last news headlines in the front index (non wordpress) page, and so far I've been able to extract the title, date and link of each post, but I don't know how to get the featured image (or any post image, for that matter).

My code is (I've taken out all the classes and stuff):

<?php
     $url="https://www.navasdelpinar.com/noticias/wp-json/wp/v2/posts?_embed&per_page=1";
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_URL,$url);
     $result=curl_exec($ch);
     $posts = json_decode($result, true);
     foreach ($posts as $post) { ?>
<?php } ?>

<div style="background-image: url(THIS IS WHERE THE IMAGE GOES)">
    <h1><?php echo $post['title']['rendered']; ?></h1>
    <p><?php echo date('j F, Y', strtotime($post['date']));?></p>
    <a href="<?php echo $post['link']; ?>">Read post</a>
</div>

Any help?

Upvotes: 0

Views: 371

Answers (2)

germanyague
germanyague

Reputation: 3

Got it.

And without CURL:

<?php
$posts = json_decode(file_get_contents('https://www.navasdelpinar.com/noticias/wp-json/wp/v2/posts?_embed&per_page=1'), true);
    foreach ( $posts as $post ) {};
?>

MEDIA LINK:

<?php echo $post[_embedded]['wp:featuredmedia']['0'][source_url]; ?> 

POST TITLE:

<?php echo $post['title']['rendered']; ?>

DATE:

<?php echo date('j M, Y', strtotime($post['date']));?>

POST LINK:

<?php echo $post['link']; ?>

Upvotes: 0

Ryan Kozak
Ryan Kozak

Reputation: 1131

If you're using _embed you can get the source url of the image like this

array_name._embedded['wp:featuredmedia']['0'].source_url

So something like,

<?php
     $url="https://www.navasdelpinar.com/noticias/wp-json/wp/v2/posts?_embed&per_page=1";
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_URL,$url);
     $result=curl_exec($ch);
     $posts = json_decode($result, true);
     foreach ($posts as $post) { ?>
<?php } ?>

<div style="background-image: url(<?php $post._embedded['wp:featuredmedia']['0'].source_url ?>)">
    <h1><?php echo $post['title']['rendered']; ?></h1>
    <p><?php echo date('j F, Y', strtotime($post['date']));?></p>
    <a href="<?php echo $post['link']; ?>">Read post</a>
</div>

Upvotes: 1

Related Questions