最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

post thumbnails - replace featured image from frontend

programmeradmin3浏览0评论

I'm using this code to add the alt text to my featured images on upload.

$image_title = get_post( $post->ID )->post_title;
// Sanitize the title:  remove hyphens, underscores & extra spaces:
$image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ',  $image_title );
// Sanitize the title:  capitalize first letter of every word (other letters lower case):
$image_title = ucwords( strtolower( $image_title ) );
// Set the image Alt-Text
add_post_meta( $post->ID, '_wp_attachment_image_alt', $image_title );

It's working and I can see it on it's database table wp_postmeta under it's post ID.

Altough it's correctly registred on the database, the featured image doesn't have the Alt text (see the image bellow)

What could be the problem?

I'm using this code to add the alt text to my featured images on upload.

$image_title = get_post( $post->ID )->post_title;
// Sanitize the title:  remove hyphens, underscores & extra spaces:
$image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ',  $image_title );
// Sanitize the title:  capitalize first letter of every word (other letters lower case):
$image_title = ucwords( strtolower( $image_title ) );
// Set the image Alt-Text
add_post_meta( $post->ID, '_wp_attachment_image_alt', $image_title );

It's working and I can see it on it's database table wp_postmeta under it's post ID.

Altough it's correctly registred on the database, the featured image doesn't have the Alt text (see the image bellow)

What could be the problem?

Share Improve this question edited Oct 31, 2019 at 9:34 bpy asked Oct 30, 2019 at 14:55 bpybpy 2995 silver badges20 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 0

I believe you need to use set_post_thumbnail to actually set featured image:

set_post_thumbnail($_POST['post_id'], $attachment_id);

It's needed to pass the image ID from the media_handle_upload like this:

First we get the new image ID

$attach_id = media_handle_upload( $file_handler, $_POST['post_id'] );

Than we prepare the content of that alt="text":

// Prepare the alt="title"
$image_title = get_post( $post->ID )->post_title;
// Sanitize the title:  remove hyphens, underscores & extra spaces:
$image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ',  $image_title );
// Sanitize the title:  capitalize first letter of every word (other letters lower case):
$image_title = ucwords( strtolower( $image_title ) );

And finaly we set the new image alt="text":

add_post_meta( $attach_id, '_wp_attachment_image_alt', $image_title );

The reason the code above was failing, was because the $post->ID is the ID of the post itself and not the attachment ID (wich is the one we need).

发布评论

评论列表(0)

  1. 暂无评论