wordpress - 在 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 并保存更新的内容?
解决方案
我认为使用过滤器最容易
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可能会更好,因为还没有对内容进行卫生处理。
推荐阅读
- c++ - 如何 typedef 命名空间限定类型?
- mysql - 我应该如何在相同的两个模型之间建立多个多对多关系?
- haskell - 在这个 hsc2hs 的 #let 构造中重复参数的目的是什么?
- node.js - 开玩笑 - 用“模拟”前缀模拟不起作用
- json - 是否有基于 WebSocket 的标准 PubSub 协议?
- json - 评估序言中的字符串术语
- jenkins - 尝试在同一台服务器上连接 Jenkins 和 Azure DevOps 时出错
- python - JSONDecodeError 期望值:第 1 行第 1 列 (char 0) 与空数组响应
- javascript - 具有某些条件的数字范围的正则表达式
- mysql - 错误代码:1265。列的数据被截断