I installed yourls on a custom short domain. Then added an acf field to posts. Then when a post is added or modified, call yourls API to get the shortlink, and save that link in the custom field
add_action('acf/save_post', 'update_related_posts', 20);
function update_related_posts($post_id) {
global $old_field_value;
// Check if the save is an auto-save, in which case we don't want to run this function
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Check if the current user has permission to edit the post
if (!current_user_can('edit_post', $post_id)) {
return;
}
// Check if the saved post is of the desired post type
if (get_post_type($post_id) !== 'post') {
return;
}
// Get submitted values.
$new_values = $_POST['acf'];
// Important add your 'your_field_key' (starting with "field_"), not the 'your_field_name'
$new_field_value = $new_values['field_64f5a1b107cec'] . $new_values['field_64f5a4153cdf5'] . $new_values['field_6504365a21af0'];
// Check if the field has changed
if ($old_field_value != $new_field_value) {
$api_url = 'http://mndn.com/yourls-api.php';
$share_url = get_sample_permalink($post_id);
$permalink = preg_replace('/\%postname\%/', $share_url[1], $share_url[0]);
$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' => $permalink,
'format' => 'json',
'action' => 'shorturl',
'signature' => '123456789'
));
$data = curl_exec($ch);
curl_close($ch);
$data = json_decode( $data );
//echo $data->shorturl;
update_field( 'shorturl', $data->shorturl, $post_id);
}
}
Then append the ACF field value to the_content()
function prefix_add_content ($content){
if ( !is_singular( 'post' ) || is_admin() ) {
return;
}
$shortlink = '<p><a href="' . get_field( 'shorturl', $post_id ) . '" target="_blank">' . get_field( 'shorturl', $post_id ) . '</p>';
$content = $content . $shortlink;
return $content;
}
add_filter ('the_content', 'prefix_add_content');