【问题标题】:WORDPRESS replace hyphens with space for $post->post_titleWORDPRESS 用空格替换 $post->post_title 的连字符
【发布时间】:2021-07-30 11:59:33
【问题描述】:

我在 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;
} 

【问题讨论】:

    标签: wordpress woocommerce alt


    【解决方案1】:

    你几乎明白了!

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

    $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;
    } 
    

    【讨论】:

    • 哦,哇,我完全惊讶于那里。非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    相关资源
    最近更新 更多