WordPress短代码问题:1984年至今年数计算代码无法运行
The main reason your shortcode isn’t working is that WordPress shortcode functions must return their output instead of echoing it. When you use echo inside the function, the content gets sent to the browser before WordPress can integrate it into the page’s content flow—this leads to unexpected placement or no visible output at all.
Additionally, there’s a small issue with how you’re initializing the current date: new DateTime('Y') isn’t a valid way to get the current year’s date. The DateTime constructor expects a proper date string, not a format character like Y. Instead, you can use new DateTime() to grab the current date and time, which will correctly calculate the year difference.
Here’s the corrected shortcode code:
function wpcs_vc_shortcode( $atts ) { $current_date = new DateTime(); $target_date = new DateTime('1984-01-01'); // Full date for clarity $diff = $target_date->diff($current_date); return $diff->y; } add_shortcode( 'year_ago_slider', 'wpcs_vc_shortcode');
Key Fixes:
- Replaced
echo $diff->ywithreturn $diff->y: This lets WordPress properly handle the output and insert it exactly where the shortcode is placed. - Fixed current date initialization:
new DateTime()correctly uses the current date instead of the invalid'Y'string. - Added a full target date (
1984-01-01) to avoid any parsing ambiguity and make the code more explicit.
If you want a more concise version (since we only care about the year difference), you can simplify the logic even further:
function wpcs_vc_shortcode( $atts ) { return date('Y') - 1984; } add_shortcode( 'year_ago_slider', 'wpcs_vc_shortcode');
This achieves the same result by subtracting the target year directly from the current year. Once you update your code with either version, the shortcode [year_ago_slider] will display the number of years since 1984 correctly wherever you use it in your WordPress content.
内容的提问来源于stack exchange,提问作者Adriano Varlotta

