You can used ACF Pro and adding some custom code to your theme’s functions.php
file.
// Add ACF fields
if( function_exists('acf_field_group') ):
acf_field_group(array(
'key' => 'group_60aaf3a3f3d4a',
'title' => 'WhatsApp Fields',
'fields' => array(
array(
'key' => 'field_60aaf3aaf3d4b',
'label' => 'WhatsApp Phone',
'name' => 'whatsapp_phone',
'type' => 'text',
'instructions' => 'Enter the WhatsApp phone number',
'required' => 1,
'default_value' => '',
),
array(
'key' => 'field_60aaf3b9f3d4c',
'label' => 'WhatsApp Message',
'name' => 'whatsapp_message',
'type' => 'text',
'instructions' => 'Enter the default WhatsApp message',
'required' => 1,
'default_value' => '',
),
array(
'key' => 'field_60aaf3d7f3d4d',
'label' => 'WhatsApp Link',
'name' => 'whatsapp_link',
'type' => 'text',
'instructions' => 'This field will be dynamically populated',
'required' => 0,
'default_value' => '',
'readonly' => 1,
'hidden' => 1,
),
),
'location' => array(
array(
array(
'param' => 'post_type',
'operator' => '==',
'value' => 'post', // Change this to your post type to your post_type_slug
),
),
),
));
endif;
// Function to dynamically generate WhatsApp link
function generate_whatsapp_link($post_id) {
// Get phone number from theme options
$whatsapp_phone = get_field('whatsapp_phone', 'option');
// Get message from post
$whatsapp_message = get_field('whatsapp_message', $post_id);
// Encode message
$encoded_message = urlencode($whatsapp_message);
// Generate WhatsApp link
$whatsapp_link = "https://wa.me/{$whatsapp_phone}?text={$encoded_message}";
// Update the whatsapp_link field value
update_field('whatsapp_link', $whatsapp_link, $post_id);
}
// Hook to update WhatsApp link when post is saved
add_action('acf/save_post', 'generate_whatsapp_link', 20);
// Shortcode to display WhatsApp link in the frontend
function whatsapp_link_shortcode($atts) {
$post_id = isset($atts['post_id']) ? intval($atts['post_id']) : get_the_ID();
return get_field('whatsapp_link', $post_id);
}
add_shortcode('acf_whatsapp_link', 'whatsapp_link_shortcode');