我想在wordpress帖子内容中使用短网址(不是帖子永久链接)。因此,当我在帖子内容中设置新链接时,我想如果这个网址会缩短服务时间。我有一个url缩短工具与yourls api,它工作正常。我的问题是,我无法将帖子中的所有长网址更改为新缩短的网址。
我的功能如下:
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' );
}
如何使用新缩短的网址替换所有长网址并保存更新的内容?
答案 0 :(得分:0)
我认为使用过滤器最容易
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,由于尚未对内容进行卫生处理,因此可能会更好。