WORDPRESS 用空格替换 $post->post_title 的连字符

我在functions.php 中使用此代码将“alt”文本设置为等于“title”,因为缺少alt 文本。

“标题”等于包含连字符的图像文件名。

这一直有效,直到我尝试使用 str_replace('-',' ',$string); 从“title”和随后的“alt”中删除连字符。

我是一个完整的编码新手,这就是为什么我的尝试不仅不起作用,而且可能会失败。

这有可能实现吗?

add_filter('wp_get_attachment_image_attributes','change_attachement_image_attributes',20,2);
function change_attachement_image_attributes($attr,$attachment) {
global $post;
$product = wc_get_product( $post->ID );
if ($post->post_type == 'product') {
    $title = $post->post_title;
    $replace = str_replace("-"," ",$title);
    $attr['alt'] = $attr['replace'];
    }
    return $attr;
} 
aabeau 回答:WORDPRESS 用空格替换 $post->post_title 的连字符

你差点就搞定了!

您的代码中有一个小错误:

$attr['alt'] = $attr['replace'];

它应该在哪里:

$attr['alt'] = $replace;

这是因为 $attr['replace'] 不存在并且 $replace 是包含您要分配给 $attr[' 的更改的变量alt']

add_filter('wp_get_attachment_image_attributes','change_attachement_image_attributes',20,2);
function change_attachement_image_attributes($attr,$attachment) {
    global $post;
    $product = wc_get_product( $post->ID );
    if ($post->post_type == 'product') {
        $title = $post->post_title;
        $replace = str_replace("-"," ",$title);
        $attr['alt'] = $replace;
    }
    return $attr;
} 
本文链接:https://www.f2er.com/10124.html

大家都在问