第一个问题是,自定义字段保存为url,而不是id。因此,您需要从url中检索附件id。首先要使用“guid”字段。
抵制诱惑,找到另一种方法:对于健壮的wordpress代码,您必须认为“guid”不存在,所以请重复“guid不存在”。
一旦“guid”不存在,我们就必须找到另一种方法,这个好方法来自here
function get_logo_id_from_url( $attachment_url = \'\' ) {
global $wpdb;
$attachment_id = false;
if ( \'\' == $attachment_url ) return;
$upload_dir_paths = wp_upload_dir();
if ( false !== strpos( $attachment_url, $upload_dir_paths[\'baseurl\'] ) ) {
$attachment_url = preg_replace(\'/-\\d+x\\d+(?=\\.(jpg|jpeg|png|gif)$)/i\',\'\',$attachment_url);
$attachment_url = str_replace($upload_dir_paths[\'baseurl\'].\'/\',\'\',$attachment_url);
$attachment_id = $wpdb->get_var( $wpdb->prepare(
"SELECT wposts.ID FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
WHERE wposts.ID = wpostmeta.post_id AND
wpostmeta.meta_key = \'_wp_attached_file\' AND
wpostmeta.meta_value = \'%s\' AND
wposts.post_type = \'attachment\'", $attachment_url ) );
}
return $attachment_id;
}
然后,我们使用前面的函数编写另一个函数:
function author_logo( $author_id = 0, $size = \'\', $alt = \'\' ) {
if ( ! intval($author_id) ) return;
$author_logo = get_field(\'author_logo\' , \'user_\' . $author_id );
if ( filter_var($author_logo, FILTER_VALIDATE_URL) ) return;
if ( empty($size) ) {
$nosize = true;
} else {
$logo_id = get_logo_id_from_url( $author_logo );
if ( ! intval($logo_id) ) {
$nosize = true;
} else {
$sizedlogo = wp_get_attachment_image_src(logo_id, $size);
$nosize = filter_var($sizedlogo[0], FILTER_VALIDATE_URL) ? false : true;
}
}
if ( $nosize ) {
return sprintf(\'<img src="%s" alt="%s" />\', $author_logo, $alt );
} else {
return sprintf(\'<img src="%s" alt="%s" />\', $sizedlogo[0], $alt );
}
}
在插件或主题中保存这些函数后
functions.php
您可以这样使用它们:
<?php
// print default size
echo author_logo( $author_id );
// print in a custom size
echo author_logo( $author_id, \'homepage-thumb\' );
// print in a custom size with custom alt text
echo author_logo( $author_id, \'homepage-thumb\', \'Author Logo\' );
?>
代码为
untested 但应该可以,除非有任何打字错误。。。