I'm using a customized version of the Last Viewed Posts plugin to grab recently viewed releases on my record label site.
The code I'm using grabs an attachment image but it is not always the page featured image - the results are intermittent. Here is the code:
function zg_recently_viewed() { // Output
echo '<ul style="list-style:none; padding-left:0px;font-size:11px;" class="viewed_posts">';
if (isset($_COOKIE["WP-LastViewedPosts"])) {
//echo "Cookie was set.<br/>"; // For bugfixing - uncomment to see if cookie was set
//echo $_COOKIE["WP-LastViewedPosts"]; // For bugfixing (cookie content)
$zg_post_IDs = unserialize(preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", stripslashes($_COOKIE["WP-LastViewedPosts"]))); // Read serialized array from cooke and unserialize it
//echo $_COOKIE["WP-LastViewedPosts"];
foreach ($zg_post_IDs as $value) { // Do output as long there are posts
global $wpdb;
$zg_get_title = $wpdb->get_results("SELECT post_title FROM $wpdb->posts WHERE ID = '$value+0' AND ID IN ( SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = '5' ) LIMIT 1");
$thumb = $wpdb->get_var("SELECT ID FROM $wpdb->posts where post_parent = '$value' and post_type = 'attachment'");
/* $thumb = $wpdb->get_var( "SELECT meta_value FROM {$wpdb->postmeta} where post_parent = '$value' AND meta_key = '_thumbnail_id'" ); */
$thumbnail = wp_get_attachment_image_src($thumb);
foreach($zg_get_title as $zg_title_out) {
if ($thumbnail) {
echo "<li style='max-width:96px;float:left;margin-right:20px;min-height:200px;'><a class='relatedimg' style='text-decoration:none;' href=\"". get_permalink($value+0) . "\" title=\"". $zg_title_out->post_title . "\"><img src='" .$thumbnail[0]. "' alt='Release Image' />" . $zg_title_out->post_title . "</a></li>\n";
} else {
echo "<li style='max-width:96px;float:left;margin-right:20px;min-height:200px;'><a class='relatedimg' style='text-decoration:none;' href=\"". get_permalink($value+0) . "\" title=\"". $zg_title_out->post_title . "\"><img src='http://vizualrecords.com/wp-content/uploads/2011/04/vizual_feature-150x150.png' alt='Release Image' />" . $zg_title_out->post_title . "</a></li>\n";
}
}
}
} else {
//echo "No cookie found."; // For bugfixing - uncomment to see if cookie was not set
}
echo '</ul>';
}
This line: $thumb = $wpdb->get_var("SELECT ID FROM $wpdb->posts where post_parent = '$value' and post_type = 'attachment'");
...grabs an image and most often will grab the featured image for the page, but not always. The commented out line below that does not work but I think that is closer to what I'm looking for.
The cookie is set in a function above this. Note that I do need to grab the featured image with a direct mysql call ($wpdb) and not using normal WP functions.
Any ideas?