Jeremiah S.
Jeremiah S.

Reputation: 421

Wordpress Post Meta only working for one post in loop

Only the first post I created is providing the url in this loop, all followings posts I create don't show the url as existing.

global $post;
$posts = get_posts(array(
    'post_type'   => 'logos',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'fields' => 'ids'
    )
);
echo "<div class='ssslider-{$slider['id']}'>";
foreach($posts as $p){

    $company_url = get_post_meta($p,"company_url",true);
    $title = get_the_title($p);
    $thumb_id = get_post_thumbnail_id($p);
    $thumb_url_array = wp_get_attachment_image_src($thumb_id, 'thumbnail-size', true);
    $thumb_url = $thumb_url_array[0];

    echo "<div style='margin:0px 40px;overflow:hidden;'><a href='{$company_url}' target='_blank'><img style='height:100px;' src='{$thumb_url}' alt='{$title}'/></a></div>";
}

echo "</div>";

Upvotes: 0

Views: 48

Answers (1)

Xhynk
Xhynk

Reputation: 13850

While it's more common to use WP_Query for this, get_posts() should work just fine.

It looks like the issue is in your use of get_post_meta().

The first argument is expected to be the Post ID and it looks like you're passing a WP_Post Object.

Note, get_post_thumbnail_id() and get_the_title() should take the ID as well, but are stated to also accept a WP_Post Object.

$posts = get_posts([
    'post_type'      => 'logos',
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'fields'         => 'ids'
]);

echo "<div class='ssslider-{$slider['id']}'>";
    foreach( $posts as $p ){
        $company_url = get_post_meta( $p->ID, 'company_url', true );
        $title       = get_the_title( $p->ID );
        $thumb_id    = get_post_thumbnail_id( $p->ID );
        $thumb_array = wp_get_attachment_image_src( $thumb_id, 'thumbnail-size', true );
        $thumb_url   = $thumb_array[0];

        echo "<div style='margin:0px 40px;overflow:hidden;'><a href='{$company_url}' target='_blank'><img style='height:100px;' src='{$thumb_url}' alt='{$title}'/></a></div>";
    }
echo "</div>";

Upvotes: 3

Related Questions