dovefromhell
dovefromhell

Reputation: 84

Php with WordPress how to call up permalinks to two separate posts

i'm building a recent posts function into a wordpress site, i've got it to call up two different featured images but they are both linking to the same post, can anyone see where i am going wrong?

<?php
        $args = array(
'posts_per_page' => 2,
'order_by' => 'date',
'order' => 'desc'
);

$post = get_posts( $args );
if($post) {
$post_id = $post[0]->ID;
if(has_post_thumbnail($post_id)){
    ?>
    <div class="grid_24">
        <div class="grid_12">
        <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
    <?php
    echo get_the_post_thumbnail($page->ID, 'medium');
    ?>
    </a>
        </div>
        <div class="grid_12">
        <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
    <?php
    echo get_the_post_thumbnail( $post_id,'medium');
    ?>
        </a>
        </div>

    </div>
    <?php

    }
}
    ?>  

Upvotes: 1

Views: 54

Answers (2)

Yuxel Yuseinov
Yuxel Yuseinov

Reputation: 340

Okay, first of all, you are not looping the query you have made ( e.g $posts = get_posts( $args ); ) you are just displaying the 1st post's thumbnail and the thumbnail of the current page.

You need to loop the post like this :

<?php
$args = array(
    'posts_per_page' => 2,
    'order_by' => 'date',
    'order' => 'desc'
);

$posts = get_posts( $args );
?>

<?php if ( !empty( $posts ) ) :?>
    <div class="grid_24">
        <?php foreach ( $posts as $post ) : ?>\
            <?php if( has_post_thumbnail( $post->ID ) ) ?>
                <div class="grid_12">
                    <a href="<?php echo esc_url( get_permalink( $post->ID ) ) ?>">
                        <?php echo get_the_post_thumbnail( $post->ID, 'size_here'); ?>
                    </a>
                </div>
            <?php endif; ?>
        <?php endforeach?>
    </div>
<?php endif;

Upvotes: 0

Chris
Chris

Reputation: 41

you can use echo get_the_permalink($post->ID) to get the uri for the posts

So it looks like in your case you'd need

echo get_the_permalink($post[0]->ID);

and

echo get_the_permalink($post[1]->ID);

in the href

However you're probably better off creating a foreach loop to go through the posts from the get_posts function

https://developer.wordpress.org/reference/functions/get_the_permalink/

https://developer.wordpress.org/reference/functions/get_posts/

Upvotes: 1

Related Questions