I am trying to create a shortcode that will take a datepicker field as input, and return the number of days until that date. How do I pass the field value to the PHP function without explicitly declaring the field slug, so I can use the function on multiple fields with different slugs?
function daysuntil_expiration_shortcode ( $atts ) {
$current_post_id = get_the_ID();
$expiration_date = ???????
$timestamp = get_post_meta($current_post_id , $expiration_date, true);
$timeleft = $timestamp - mktime();
return round ($timeleft/(60*60*24));
}
add_shortcode( 'daysuntil', 'daysuntil_expiration_shortcode' );
for example, I want a code that can be used like this:
[daysuntil [types field="insurance_expiration_date" style='text' format='m/d/y'][/types]]
With it returning a number like 30, meaning that the date in "insurance_expiration_date" is 30 days in the future, so I can compare it to a constant in a conditional.
After more research, I think i might be able to accomplish what I am after using the functions listed here:
https://toolset.com/documentation/user-guides/views/date-filters/
But I am confused on which one to use and how to use it.
For example, if I want to test for the field "expiration" to be 30 days or less in the future, how would I write that?
[wpv-conditional if="( $(wpcf-expiration) lte 'FUTURE_DAY(30)' )"]
Hello,
You can pass the parameter to your custom shortcode with attribute, see WP document:
https://developer.wordpress.org/reference/functions/add_shortcode/
For example:
function daysuntil_expiration_shortcode( $atts ) {
$atts = shortcode_atts( array(
'expiration_date' => '',
), $atts);
$res = '';
if($atts['expiration_date']){
$expiration_date = do_shortcode($atts['expiration_date']);
$timeleft = $expiration_date - current_time('timestamp');
$res = round ($timeleft/(60*60*24));
}
return $res;
}
add_shortcode( 'daysuntil', 'daysuntil_expiration_shortcode' );
Use above shortcode like this:
[daysuntil expiration_date="[types field="insurance_expiration_date" style='text' format='U'][/types]"]
My issue is resolved now. Thank you!