从标题帖子中获取alt属性(代码不起作用)

时间:2018-06-05 作者:PhineasD

我发现以下代码可以在每次我上传和在Wordpress中创建图像时填充ALT属性。代码获取图像的名称以填充属性,但我希望他获取标题帖子,如何修改它?我试图改变get_post( $post_ID )->post_titleget_the_title($page->ID) 但不起作用。非常感谢!

add_action( \'add_attachment\', \'my_set_image_meta_upon_image_upload\' );

function my_set_image_meta_upon_image_upload( $post_ID ) {
    // Check if uploaded file is an image, else do nothing
    if ( wp_attachment_is_image( $post_ID ) ) {
        $my_image_title = get_post( $post_ID )->post_title;

        // Sanitize the title: remove hyphens, underscores & extra
        // spaces:
        $my_image_title = preg_replace( \'%\\s*[-_\\s]+\\s*%\', \' \', $my_image_title );

        // Sanitize the title: capitalize first letter of every word
        // (other letters lower case):
        $my_image_title = ucwords( strtolower( $my_image_title ) );

        // Create an array with the image meta (Title, Caption,
        // Description) to be updated
        // Note: comment out the Excerpt/Caption or Content/Description
        // lines if not needed
        $my_image_meta = array(

            // Specify the image (ID) to be updated
            \'ID\' => $post_ID,

            // Set image Title to sanitized title
            \'post_title\' => $my_image_title,

            // Set image Caption (Excerpt) to sanitized title
            \'post_excerpt\' => $my_image_title,

            // Set image Description (Content) to sanitized title
            \'post_content\' => $my_image_title,
        );

        // Set the image Alt-Text
        update_post_meta( $post_ID, \'_wp_attachment_image_alt\', $my_image_title );

        // Set the image meta (e.g. Title, Excerpt, Content)
        wp_update_post( $my_image_meta );
    }
}

1 个回复
最合适的回答,由SO网友:Krzysiek Dróżdż 整理而成

嗯,换衣服get_post( $post_ID )->post_titleget_the_title($page->ID) 不起作用,因为变量$page 未在函数中的任何位置定义。。。

如果你看看add_attachment 钩子,然后您将看到它只需要一个参数:

$post\\U ID-(int)附件ID。

所以你没有贴子的ID。老实说,你不能有这样的帖子,因为附件可以直接上传到媒体库中,所以不会附加到任何帖子上。。。

但是add_attachment 当帖子已经在DB中时,会调用操作,因此您可以获取它的父帖子(如果附件已上载到某篇帖子,则该帖子将设置为父帖子)。

所以像这样的方法可能会奏效:

add_action( \'add_attachment\', \'my_set_image_meta_upon_image_upload\' );

function my_set_image_meta_upon_image_upload( $post_ID ) {
    // Check if uploaded file is an image, else do nothing
    if ( wp_attachment_is_image( $post_ID ) ) {
        $attachment = get_post( $post_ID );
        $my_image_title = $attachment->post_title;

        if ( $attachment->post_parent ) { // if it has parent, use it\'s title instead
            $my_image_title = get_post_field( \'post_title\', $attachment->post_parent );
        }

        ... // rest of the code

        wp_update_post( $my_image_meta );
    }
}

结束

相关推荐

Duplicate images in wordpress

我在我的网站上使用wordpress,但“博客”部分(这里称为新闻和事件)有问题。为什么第一张图片会被复制-http://www.fiumanofineart.com/news-events/我试过修复它,但我不能。。。任何帮助都会很好,谢谢