0

我正在使用 Wordpress 4.5。之前我使用本地服务器存储图片(包括精选图片,例如:wp-content/uploads/2016/03/aaabbbccc.jpg)。现在我想将它移动到 AWS S3 Bucket 和 Cloudfront,我不想在 Wordpress 的数据库中进行更改,并决定编写一个插件来加入我的 cloudfront 域(替换当前域),以便wp-content每次从数据库中检索时进行链接,如:https ://xxyyzzqqaa.cloudfront.net/wp-content/uploads/2016/03/aaabbbccc.jpg 。

我在我的插件中使用了一个动作钩子:

add_action( 'the_post', 'change_featured_image' );

现在我不知道下一步该怎么办?请给我一些建议,提前谢谢!

4

1 回答 1

0

我找到了解决我的问题的方法,这很容易,但我是 WP 的新手,所以我看不到这个。

在您的插件中,或者您想在 WP 加载时捕获此事件的位置,添加此过滤器:
add_filter( 'post_thumbnail_html', 'change_featured_image' );
和:

  • post_thumbnail_html是 WP 的内置过滤器。
  • change_featured_image是函数,用户定义,并在 post_thumbnail_html 返回其结果之前运行。

我对这个函数有些困惑,我不知道获取值的变量。最后,我在 WP API 文档中找到了,每个 vars 内置过滤器使用,你也可以使用。

这是示例代码:

function change_featured_image($attr)
{

    global $wpdb;

    $opt = get_option('s3dcs_status');//My value in `wp_options`
    if(empty($opt)) echo $attr;
    else{
        /// Preparing variables
        $pattern = '~(http.*\.)(jpe?g|png|[tg]iff?|svg)~i';
           $m = preg_match_all($pattern,$attro,$matches);
        $il = $matches[0][0];
        $tail = explode("wp-content", $il)[1];
        $s3dcs_remote_link = get_option('s3dcs_cfs3in') . "/wp-content" . $tail;
               echo str_replace($il, $s3dcs_remote_link, $attr) ;
    }   
}

就这样。如果您有问题,请在此处发布,让每个人都知道。

于 2016-04-29T10:41:45.340 回答