我希望WordPress返回第一张帖子图片,如果没有设置特色图片,则返回默认图片。我的主题使用the_post_thumbnail
很多次,所以我不想遍历并更改对新函数的所有引用。我宁愿过滤核心。以下是我添加的内容functions.php
:
add_filter(\'post_thumbnail_html\', \'my_thumbnail_html\', 10, 5);
function my_thumbnail_html( $html, $post_id, $post_thumbnail_id, $size, $attr ) {
global $post, $posts;
if (has_post_thumbnail() ) {
echo get_the_post_thumbnail( null, $size, $attr );
}
else {
$first_img = \'\';
ob_start();
ob_end_clean();
$output = preg_match_all(\'/<img.+src=[\\\'"]([^\\\'"]+)[\\\'"].*>/i\', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){
$first_img = get_bloginfo("template_url") . \'/images/default.gif\';
}
return $first_img;
}
}
如何正确钩住它?
最合适的回答,由SO网友:Zade 整理而成
Figured it out:
function get_attachment_id_from_src( $image_src ) {
global $wpdb;
$query = "SELECT ID FROM {$wpdb->posts} WHERE guid=\'$image_src\'";
$id = $wpdb->get_var($query);
return $id;
}
add_filter( \'post_thumbnail_html\', \'my_post_image_html\', 10, 5 );
function my_post_image_html( $html, $post_id, $post_thumbnail_id, $size, $attr ) {
if( \'\' == $html ) {
global $post, $posts;
ob_start();
ob_end_clean();
$output = preg_match_all(\'/<img.+src=[\\\'"]([^\\\'"]+)[\\\'"].*>/i\', $post->post_content, $matches);
$first_img = $matches [1] [0];
if ( empty( $first_img ) ){
$image_id = 129; // default image ID
}
else {
$image_id = get_attachment_id_from_src($first_img);
}
$html = wp_get_attachment_image( $image_id, $size, false, $attr );
}
return $html;
}