用帖子中每个图像的过滤器替换 alt 和标题(WordPress)

问题描述 投票:0回答:2

我已经使用媒体库中正确的 alt 和标题信息更新了 WordPress 中的数百张图像,现在我需要让页面呈现正确的信息,而无需单独更新每个页面。

似乎使用

add_filter
或类似的东西就可以满足我的需要,但我不确定是否需要找出正则表达式,或者我是否可以只使用
the_content

我已经整理了一种方法来获取所有附加图像并显示正确的 alt 和标题标签,但我只知道如何将图像添加到

the_content
的开头或结尾。我需要它来替换已经存在的每个相应图像。有一个更好的方法吗?这是一个将新图像内容放入数组的函数:

function replaceimages_get_images($content) {
    global $post;
    $images = array();
    $x = 0;
    $args = array(
        'post_type'   => 'attachment',
        'numberposts' => -1,
        'post_status' => null,
        'post_parent' => $post->ID,
        'exclude'     => get_post_thumbnail_id()
    );

    $attachments = get_posts( $args );
    if ( $attachments ) {
        foreach ( $attachments as $attachment ) {
            $src = wp_get_attachment_image_src( $attachment->ID, 'full' );
            $title = apply_filters( 'the_title', $attachment->post_title );
            $alt = apply_filters( 'alt', get_post_meta($attachment->ID, '_wp_attachment_image_alt', true ));
            $images[$x] = '<img src="'.$src[0].'" title="'.$title.'" alt="'.$alt.'" />';
            $x++;
        }
    }
    return $content;
}
add_filter( 'the_content', 'replaceimages_get_images' );

我现在需要用伪代码执行以下操作:

for each image in $content {
    match src to image in array;
    replace entire image with image from array;
}
php regex wordpress alt add-filter
2个回答
3
投票

您的方法几乎在每次页面加载时都会消耗资源。我建议只执行一次并直接在数据库中修复所有图像属性,但问题太广泛,我只会概述步骤。

  1. 备份数据库。

  2. 获取所有图片附件

    $args = array(
            'post_type'       => 'attachment',
            'post_mime_type'  => 'image',
            'numberposts'     => -1
        );
    
  3. 使用

    guid
    wp_get_attachment_url
    获取图像URL

  4. 在数据库中搜索URL

    // $image_url = your_method_to_get_it();
    $sql_results = $wpdb->get_results(
         $wpdb->prepare( "
            SELECT *
                FROM $wpdb->posts
            WHERE post_content 
                LIKE %s
            AND post_status = 'publish'
             " 
            ,'%' . like_escape( $image_url ) . '%'
        )
    );
    
  5. post_content
    do_your_magic( $image_attributes, $post_content )
    解析 HTML。
    不要使用正则表达式,
    DomDocument
    可以完成这项工作。

  6. 更新帖子

    wp_update_post


这是一个帮助插件来执行此操作。请注意

  • 我们可以使用 URL 中的查询参数有选择地触发操作

    http://example.com/wp-admin/admin.php?page=updating-images&doit
  • 你必须一步步构建它,

    var_dump
    一切都,直到你准备好第6步

<?php
/* Plugin Name: (SO) Updating Images */

add_action('admin_menu', 'helper_so_19816690' );

function helper_so_19816690() 
{
    add_menu_page(
        'Updating Images',
        'Updating Images',
        'add_users',
        'updating-images',
        'doit_so_19816690',
        null,
        0
    );
}

function doit_so_19816690()
{ 
    echo '<h2>Conversion</h2>';
    $args = array(
            'post_type'      => 'attachment',
            'post_mime_type' => 'image',
            'numberposts'    => -1
        );
    $attachments = get_posts( $args );

    # Our thing
    if( isset( $_GET['doit'] ) )
    {
        var_dump( $attachments );
    }
}

0
投票

我知道这篇文章很旧,但今天我需要一个残酷的快速脚本,所以我构建了 brasofilo 正在谈论的内容,并认为如果我将其发布在这里,它可能会帮助另一个灵魂。

这将作为 WP 插件使用,但请在运行之前通读它,并且除非您备份了数据库,否则不要运行它。

  1. 将文件放入您的
    /wp-content/plugins/
  2. 在 wp-admin 中激活插件
  3. &i_swear_i_backed_it_up=1
    添加到 wp-admin url...
<?php
/*
Plugin Name: Image alt updater
Plugin URI: http://woodyhayday.com
Description: Brutal image alt attribute updater - finds images without alt's and does its best (read before using, demo only)
Version: 0.1
Author: <a href="http://woodyhayday.com">Woody Hayday</a>
*/

#} Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit; 

// Works through attachment images and checks all published 
// posts to see if each image has an `alt` attribute
// ... where they don't it makes one up from filename or post title
// Use with caution, and always backup your database before running!
function wordPress_alt_image_updater(){ 

    // HAVE YOU BACKED UP YOUR DB? RLY?
    if ( isset( $_GET['i_swear_i_backed_it_up'] ) ){

        // got rights?
        if (!current_user_can('manage_options'))  { wp_die( __('You do not have sufficient permissions to access this page.','projectpages') ); }

        // get image attachments
        echo '<h2>Image alt attribute updater</h2>';
        $args = array(
                'post_type'      => 'attachment',
                'post_mime_type' => 'image',
                'numberposts'    => -1
            );
        $attachments = get_posts( $args );

        echo 'Found '.count($attachments).' image attachments<br>';

        if ( !isset( $_GET['doit'] ) ){

            echo 'Add `?doit=1` to your url when you\'re ready, and your database has been backed up.<br>';

        } else {

            // general counts
            $updated_count = 0;
            $filled_alt_count = 0;
            $empty_alt_count = 0;

            echo '<h2>Processing...</h2>';

            global $wpdb;

            // if you have LOTS of images, put paging in here
            foreach ( $attachments as $attachment_post ){

                $image_url = $attachment_post->guid;

                echo '<strong>'.$image_url.'</strong><br>';

                // get post content of posts with this image
                $sql_results = $wpdb->get_results(
                    $wpdb->prepare( "
                        SELECT *
                            FROM $wpdb->posts
                        WHERE post_content 
                            LIKE %s
                        AND post_status = 'publish'
                         " 
                        ,'%' . like_escape( $image_url ) . '%'
                    )
                );

                // got posts with this image url in?
                if ( is_array( $sql_results ) && count( $sql_results ) > 0 ){

                    echo 'Found in '. count( $sql_results ) . ' posts.<br>';

                    // this is only hitting first instance, doesn't allow for repeat images
                    // you may need to tweak, depending on your image use case
                    foreach ( $sql_results as $post ){

                        echo '<hr>Post: '.$post->ID.'...<br>';

                        $alt = '';

                        // pull the <img> string
                        $img_src_pos = strpos( $post->post_content, 'src="' . $image_url . '"' );
                        if ( $img_src_pos ){

                            // working backwards, find <img
                            $img_opening_tag_pos = strrpos( substr( $post->post_content, 0, $img_src_pos ), '<img ' );

                            if ( $img_opening_tag_pos ){

                                // get closing tag
                                $img_closing_tag_pos = strpos( substr( $post->post_content, $img_src_pos ), "/>" ) + 2 + $img_src_pos;

                                if ( $img_closing_tag_pos ){

                                    $image_html = substr( $post->post_content, $img_opening_tag_pos, ($img_closing_tag_pos - $img_opening_tag_pos) );

                                    echo 'Got image html...<br>';
                                    //echo '<pre>' . esc_html( $image_html ) . '</pre>';

                                    // check for alt
                                    $alt_opening_pos = strpos( $image_html, 'alt="' ) + 5;
                                    if ( $alt_opening_pos ){

                                        // get the alt
                                        $alt = substr( $image_html, $alt_opening_pos, strpos( substr( $image_html, $alt_opening_pos ), '"' ) );

                                        echo 'Image already has a value for alt..."' . $alt . '"<br>';                                  

                                    }

                                
                                    if ( empty( $alt ) ){

                                        $new_alt = '';
                                        $empty_alt_count++;

                                        echo 'Found an image with an empty, or no alt...<br><pre>' . esc_html( $image_html ) . '</pre>';


                                        // try and generate a new alt
                                        $src_opening_pos = ( strpos( $image_html, 'src="' ) + 5 );

                                            // filename
                                            $image_file_url = substr( $image_html, $src_opening_pos, strpos( substr( $image_html, $src_opening_pos ), '"' ) );

                                            // parsed path
                                            $path = parse_url($image_file_url, PHP_URL_PATH);
                                            $image_file_name = basename($path);
                                            $image_file_slug = substr($image_file_name, 0 , (strrpos($image_file_name, ".")));

                                            // split by, and remove - + _ + .
                                            $image_file_slug = str_replace( '_', ' ', str_replace( '-', ' ', str_replace( '.', ' ', $image_file_slug ) ) );

                                            if ( !empty( $image_file_slug ) ){

                                                $new_alt = ucwords( $image_file_slug );

                                            }

                                            // remove any trailing -1 -2 etc.
                                            if ( substr( $new_alt, -2 ) == ' 1' ){ $new_alt = substr( $new_alt, 0, strlen( $new_alt ) - 2 ); }
                                            if ( substr( $new_alt, -2 ) == ' 2' ){ $new_alt = substr( $new_alt, 0, strlen( $new_alt ) - 2 ); }

                                            // (+-) post title
                                            /*$post_title = $post->post_title;

                                            if ( !empty( $post->post_title ) ){

                                                if ( !empty( $new_alt ) ){

                                                    // append break
                                                    $new_alt .= ' - ';

                                                }

                                                $new_alt .= $post->post_title;

                                            } */

                                            // any last minute proj-specific tweaks:
                                            $new_alt = str_replace( 'Cfs ', 'CFS ', $new_alt );
                                            $new_alt = str_replace( 'Me ', 'ME ', $new_alt );


                                            echo 'New alt generated: "' . $new_alt . '"<br>';


                                            // slice and dice, inject the new <img> html with alt
                                            $new_img_html = $image_html;
                                            if ( strpos( $image_html, 'alt=""' ) ){

                                                // straight replace
                                                $new_img_html = str_replace( 'alt=""', 'alt="' . esc_attr( $new_alt ) . '"', $image_html );

                                            } else {
                                                
                                                // not found, inject
                                                $new_img_html = str_replace( '/>', ' alt="' . esc_attr( $new_alt ) . '"/>', $image_html );

                                            }

                                            echo 'This:<pre>' . esc_html( $image_html ) . '</pre><br>Will be replaced with:<pre>' . esc_html( $new_img_html ) . '</pre>';

                                            // update it, if changed
                                            if ( $new_img_html !== $image_html ){

                                                $post_to_update = $post;
                                                $post_to_update->post_content = str_replace( $image_html, $new_img_html, $post->post_content );
                                                
                                                $outcome = wp_update_post( $post_to_update );

                                                echo 'Updated post ' . $post->ID . ': <a href="'.$post->guid.'" target="_blank">View</a><br>';                                          

                                            }



                                        $updated_count++;

                                    } else {

                                        $filled_alt_count++;

                                    }                                       

                                }
                            }

                            // useful stop, if you want to step through :) 
                            //if ( $updated_count > 5 ) exit();

                        }

                        echo '<hr>';

                    }

                } else {

                    echo 'Not found in any post html.<br><hr>';
                }

            }

            // summary
            echo '<hr><hr><h1>Summary</h1>';
            echo count( $attachments ) . ' attachments processed<br>';
            echo $filled_alt_count . ' images found with alt already present<br>';
            echo $empty_alt_count . ' images found with no alt<br>';
            echo $updated_count . ' alt updates made to post html<br>';
            echo 'Note! This script is flawed! It was written quickly for a specific use case, it may miss some alts, or mangle your db. Please triple check your data.';

        }

        exit();

    }

} add_action( 'init' , 'wordPress_alt_image_updater');
© www.soinside.com 2019 - 2024. All rights reserved.