0

我正在寻找修改 Wordpress 插件中的一个函数,我在其中切换到多站点安装中的主站点以加载图像。该插件会定期维护,因此我不想修改代码以便能够轻松更新它。

无论如何要“挂钩”到函数中,以便我可以这样修改它?我在下面展示了我想要实现的目标,我必须手动添加switch_to_blog(1)restore_current_blog().

function get_value($post_id, $field)
{
    $value = parent::get_value($post_id, $field);

    switch_to_blog(1);

    $attachments = get_posts(array(
        'post_type' => 'attachment',
        'post_status' => null,
        'post__in' => $value,
    ));

    $ordered_attachments = array();
    foreach( $attachments as $attachment)
    {
        $ordered_attachments[ $attachment->ID ] = array(
            'id' => $attachment->ID,
            'alt' => get_post_meta($attachment->ID, 
                        '_wp_attachment_image_alt', true),
            'title' => $attachment->post_title,
        );
    }

    restore_current_blog();

    return $ordered_attachments;
}
4

3 回答 3

2

不,如果开发人员编写了“do_action”行代码,您只能“挂钩”到函数中。如果不是这种情况,您可以创建该函数的副本并调用您的副本而不是原始的,但是如果在插件内部调用该函数,您可以什么都不做,只能修改插件(如您所说,这不是一个好主意)

于 2012-12-18T15:22:02.813 回答
2

请原作者拆分功能:

function get_ordered_attachments_by_field($post_id, $field)
{
    $value = parent::get_value($post_id, $field);

    return get_ordered_attachments($value);
}

function get_ordered_attachments($value)
{
    $attachments = get_posts(array(
        'post_type' => 'attachment',
        'post_status' => null,
        'post__in' => $value,
    ));

    $ordered_attachments = array();
    foreach ($attachments as $attachment)
    {
        $ordered_attachments[ $attachment->ID ] = array(
            'id' => $attachment->ID,
            'alt' => get_post_meta($attachment->ID, 
                        '_wp_attachment_image_alt', true),
            'title' => $attachment->post_title,
        );
    }

    return $ordered_attachments;
}

然后,您可以更轻松地与您需要的功能进行交互,例如

    $value = $object->get_value($post_id, $field)
    switch_to_blog(1);
    $attachments = $object->get_ordered_attachments($value);
    restore_current_blog();

And the job is done. The benefit for the project is that they have reduced (at least a little bit) the lines of code in the attachment function and made it more concrete what the function does by it's name. No idea what that object is, if it's a plugin this looks anyway like a place to store functions in, so create more and more functions, but smaller ones.

于 2012-12-18T15:30:58.393 回答
1

您可以通过将替换函数放在存储在wp-contents/mu-plugins

您应该检查以确保原始函数位于if()检查它是否已存在的块内。如果不是,那么这种方法将不起作用。

于 2012-12-18T15:26:17.420 回答