1

I have some Pinterest code to show a Pin it button on my wordpress posts but it only grabs the post thumbnail. What I want is to grab the first post content image and only grab the thumbnail if there are no images in the post!??

Have tried tons of examples but nothing works.

<a href="http://pinterest.com/pin/create/button/?url=<?php the_permalink(); ?>&media=<?php $thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail' ); echo $thumb['0']; ?>&description=<?php the_title(); ?>" class="pin-it-button" count-layout="horizontal">Pin It</a>
4

1 回答 1

2

您可以试试这个,只需将以下功能粘贴到您的functions.php

function get_first_image()
{
    global $post, $posts;
    $first_img = '';
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
    $first_img = $matches [1][0];
    if(empty($first_img)) $first_img = false;
    return $first_img;
}

在您的Pinterest代码获取图像之前

$thumb=get_first_image();
if(!$thumb)
{
    $thumb=wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'thumbnail' );
    $thumb=$thumb[0];
}

然后在你的Pinterest链接media=<?php echo $thumb; ?>

<a href="http://pinterest.com/pin/create/button/?url=<?php the_permalink(); ?>&media=<?php echo $thumb; ?>&description=<?php the_title(); ?>" class="pin-it-button" count-layout="horizontal">Pin It</a>
于 2012-06-23T02:55:12.120 回答