I am building a plugin which has to do with donations and I added a progress bar whose value has to be read from the database.
For example, if I added my shortcode on /sample-page/
and the value at that moment in the database is 1000
, even if I update the value in the database, the value showing on /sample-page/
does not change unless the url change for example /smaple-page/?something=s
then it would load new content and then if the value changes in the database again, I'll need to change the URL for it to render the latest content.
Please help
You can find the code below
add_shortcode( $this->donationProgressShortCode, array($this,'progressBarShortCode'));
function progressBarShortCode($params){
if(!isset($params['id']) || !$params['id']){
return 'ID NOT PROVIDED';
}
$model = new Donation();
$donation = $model->getDonation($params['id']);
if(!$donation){
return;
}
$target = $donation->target;
if($target <= 0){
return;
}
$total = 0;
$percentage = 0;
$transactions = $model->getTransactions($params['id']);
if($transactions){
foreach($transactions as $item){
// error_log('ITEMS HERE MAN: '.json_encode($item));
$total+= $item->amount;
}
}
if($total > 0){
$percentage = ($total * 100) / $target;
}
wp_enqueue_style('tz_payment_gateway_style', $this->pluginUrl . 'assets/style/checkout-style.css');
$content = '<div style="width: 100%; padding: 2px">
<div style="display: flex; justify-content-between; font-weight: bold">
<div style="width: 100%;">'.$total.'<small>'.$donation->currency.'</small></div>
<div style="width: 100%; text-align: right">'.$target.'<small>'.$donation->currency.'</small></div>
</div>
<div style="position: relative; background-color: #ccc9; border-radius: 5px; overflow: hidden; height: 18px">
<div style="transition: 11.5s all ease-in; height: 18px; background-color: '.$donation->background_color.'; position: absolute; width:'.($percentage> 100? 100: $percentage).'%; color: transparent">.</div>
<div style="height: 18px; line-height: 18px; text-shadow: 1px 1px 2px black; color: #fff; width: 100%; position: absolute; text-align: center;">'.$percentage.'%</div>
</div>
</div>';
return $content;
}
What I do is basically read all paid transactions from the database then calculate the percentage based on the target amount, then render the result as a progress bar as seen in the image below.
This requires having JavaScript execute a request from the browser to your server at a regular interval. You will likely need to set up a custom REST API endpoint to receive requests from the browser via your shortcode. The REST API endpoint would respond with the latest updated value, and your JavaScript would update the web page with this new value.
The server cannot regularly and automatically push data updates to the browser. The browser must regularly send requests to the server. This is why using a different URL worked to update the donations. The browser was making another request to the server.