1

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

似乎 usingadd_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;
}
4

1 回答 1

3

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

  1. 备份数据库。

  2. 获取所有图片附件

    $args = array(
            'post_type'       => 'attachment',
            'post_mime_type'  => 'image',
            'numberposts'     => -1
        );
    
  3. 使用guidorwp_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从和解析 HTML do_your_magic( $image_attributes, $post_content )
    不要使用正则表达式,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 );
    }
}
于 2013-11-06T19:52:05.457 回答