有两种可能的解决方案。
Solution 1: 由于Options Framework只提供上载程序,因此我假设您是在WP admin端手动输入alt文本。您可以为alt文本创建一个文本选项,以便从自定义选项面板中输入。然后只需在需要的地方重复该选项:
$options[] = array(
\'name\' => __(\'Header Overlay Alt Text\', \'options_framework_theme\'),
\'desc\' => __(\'Alternate text for your header overlay image.\', \'options_framework_theme\'),
\'id\' => \'header_overlay_alt\',
\'type\' => \'text\');
然后在模板中:
<img src="<?php echo of_get_option(\'header_overlay\'); ?>" alt="<?php echo of_get_option(\'header_overlay_alt\'); ?>">
或
Solution 2: (这更直接地回答了您的问题。)
a)根据URL检索附件ID,b)使用该ID检索相应的alt文本。(a部分归功于Philip Newcomer:http://philipnewcomer.net/2012/11/get-the-attachment-id-from-an-image-url-in-wordpress/.)
function pn_get_attachment_id_from_url( $attachment_url = \'\' ) {
global $wpdb;
$attachment_id = false;
// If there is no url, return.
if ( \'\' == $attachment_url )
return;
// Get the upload directory paths
$upload_dir_paths = wp_upload_dir();
// Make sure the upload path base directory exists in the attachment URL, to verify that we\'re working with a media library image
if ( false !== strpos( $attachment_url, $upload_dir_paths[\'baseurl\'] ) ) {
// If this is the URL of an auto-generated thumbnail, get the URL of the original image
$attachment_url = preg_replace( \'/-\\d+x\\d+(?=\\.(jpg|jpeg|png|gif)$)/i\', \'\', $attachment_url );
// Remove the upload path base directory from the attachment URL
$attachment_url = str_replace( $upload_dir_paths[\'baseurl\'] . \'/\', \'\', $attachment_url );
// Finally, run a custom database query to get the attachment ID from the modified 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;
}
$your_id = pn_get_attachment_id_from_url(of_get_option(\'header_overlay\'));
$alt_text = get_post_meta($your_id, \'_wp_attachment_image_alt\', true);
然后根据需要进行回声输出:
<img src="<?php echo of_get_option(\'header_overlay\'); ?>" alt="<?php echo $alt_text; ?>">
我知道这个问题已经问了6个月了,但即使OP已经开始了,希望这个答案能帮助一些人!