首页 > 解决方案 > 在 Wordpress 中替换保存/更新后的链接

问题描述

我想在 wordpress 帖子内容中使用短网址(而不是帖子永久链接)。所以当我在我的帖子内容中设置一个新链接时,我想这个网址是否会被服务缩短。我有一个带有 yourls api 的 url 缩短工具,它工作正常。我的问题是,我无法将帖子中的所有长网址更改为新的缩短网址。

我的功能如下所示:

 add_action( 'save_post', 'save_book_meta', 10, 3 );
 function save_book_meta( $post_id, $post, $update ) {
 global $wpdb;

 preg_match_all('|<a.*(?=href=\"([^\"]*)\")[^>]*>([^<]*)</a>|i', $post->post_content, $match);

 $new_content = $post->post_content;

 foreach($match[1] as $link){
     $yapikey = '********';
     $api_url =  'https://yourdomain.com/yourls-api.php';
     $longUrl = $link;

     // Init the CURL session
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $api_url);
     curl_setopt($ch, CURLOPT_HEADER, 0);            // No header in the result
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return, do not echo result
     curl_setopt($ch, CURLOPT_POST, 1);              // This is a POST request
     curl_setopt($ch, CURLOPT_POSTFIELDS, array(     // Data to POST
             'url' => $longUrl,
             'format'   => 'json',
             'action'   => 'shorturl',
             'signature' => $yapikey
         ));

     // Fetch and return content
     $data = curl_exec($ch);
     curl_close($ch);

     // Do something with the result. Here, we echo the long URL
     $data = json_decode( $data );

     if($data->shorturl) {
         str_replace($link, $data->shorturl, $new_content);
     }
 }

 // unhook this function so it doesn't loop infinitely
 remove_action('save_post', 'save_book_meta' );

 $post_new = array(
     'ID'       => $post_id,
     'post_content'  => $new_content
   );

 $post_id = wp_update_post( $post_new, true );
 add_action( 'save_post', 'save_book_meta' );

}

如何用新的缩短 url 替换所有长 url 并保存更新的内容?

标签: wordpressurl-shortener

解决方案


我认为使用过滤器最容易

add_filter( 'wp_insert_post_data' , 'save_book_meta' , '99', 2 ); 

function save_book_meta( $data , $postarr ) {
    // find your urls and do the replacements on $data['post_content'] here
    return $data;
}

编辑:看起来另一个可行的过滤器选项是https://codex.wordpress.org/Plugin_API/Filter_Reference/content_save_pre可能会更好,因为还没有对内容进行卫生处理。


推荐阅读