Call ACF field in PHP function - php

I have this PHP function to add a scheduled banner to my website. I want to make it workable with ACF fields.
The function:
function holiday_site_banner() {
$from_time = new DateTime( 'get_field('banner_start_date')' );
$to_time = new DateTime( 'get_field('banner_end_date')' );
if ( new DateTime() > $from_time && new DateTime() < $to_time ) {
?><div class="site-banner">
<span>
<strong style="">ⓘ LET OP:</strong> <?php get_field('banner_message')?>
</span>
</div><?php
}
}
add_action( 'wp_footer', 'holiday_site_banner' );
I tried to use the get_field for implementing the ACF values in $from_time and $to_time but it doens't work.
I set the ACF field for this as a datepicker with output Y-m-d H:i, named [banner_start_date] and [banner_end_date].
Then I also have a ACF textarea field named [banner_message] to place in between the <span>tags as you can see which also not works.
The ACF fields are added to a custom option page created with this code:
if( function_exists('acf_add_options_page') ) {
acf_add_options_page(array(
'page_title' => 'DWD Vakantiesluiting',
'menu_title' => 'DWD Vakantie',
'menu_slug' => 'dwd-vakantiesluiting',
'capability' => 'edit_posts',
'icon_url' => 'dashicons-lock',
'redirect' => true,
'updated_message' => __("Vakantiemodus ingesteld", 'acf'),
));
}
I modified the code to this but that still doesn't work:
function scheduled_site_banner() {
// Get the start and end date values from ACF fields
$start_date = get_field('banner_start_date', 'option');
$end_date = get_field('banner_end_date', 'option');
$banner_message = get_field('banner_message', 'option');
// Create DateTime objects for the start and end date
$start_time = new DateTime($start_date);
$end_time = new DateTime($end_date);
// Format the start and end date
$formatted_start_date = date("F j, Y",strtotime($start_date));
$formatted_end_date = date("F j, Y",strtotime($end_date));
// Check if the current date and time falls between the start and end dates
if ( new DateTime() > $start_time && new DateTime() < $end_time ) {
?>
<div class="site-banner">
<span>
<strong>Important Notice:</strong> <?php echo $banner_message; ?> Our site-wide banner is scheduled to display from <?php echo $formatted_start_date ?> to <?php echo $formatted_end_date ?>
</span>
</div>
<?php
}
}
add_action( 'wp_footer', 'scheduled_site_banner' );
Also using double quotations marks in // Get the start and end date values from ACF fields doesn't work.
Is there anyone who could help me with this?
Thanks in advance!

I got it done, thanks for the help. The problem was the date format among some other things. I also added Europe/Amsterdam Timezone.
This is the correct code:
function scheduled_site_banner() {
// Get the start and end date values from ACF fields
$start_date = get_field("banner_start_date", "option");
$end_date = get_field("banner_end_date", "option");
$banner_message = get_field("banner_message", "option");
// Create DateTime objects for the start and end date and set Amsterdam timezone
$start_time = DateTime::createFromFormat("Y-m-d H:i:s", $start_date, new DateTimeZone('Europe/Amsterdam'));
$end_time = DateTime::createFromFormat("Y-m-d H:i:s", $end_date, new DateTimeZone('Europe/Amsterdam'));
if($start_time === false || $end_time === false) {
// date is not in correct format
return;
}
// Check if the current date and time falls between the start and end dates
if ( new DateTime('Europe/Amsterdam') > $start_time && new DateTime('Europe/Amsterdam') < $end_time ) {
?>
<div class="site-banner">
<span>
<strong>Important:</strong> <?php echo $banner_message; ?>
</span>
</div>
<?php
}
}
add_action( 'wp_footer', 'scheduled_site_banner' );
add_filter('acf/format_value', 'do_shortcode');
I also added 2 shortcodes which can be used in the message to display the start and enddates which are set in the acf fields. I used this code for that:
function register_acf_shortcodes() {
add_shortcode('begin_vakantie', 'acf_banner_start_date_shortcode');
add_shortcode('einde_vakantie', 'acf_banner_end_date_shortcode');
}
add_action( 'init', 'register_acf_shortcodes');
function acf_banner_start_date_shortcode() {
$start_date = get_field('banner_start_date', 'option');
return date('d-m-Y', strtotime($start_date));
}
function acf_banner_end_date_shortcode() {
$end_date = get_field('banner_end_date', 'option');
return date('d-m-Y', strtotime($end_date));
}
And added this filter to the function scheduled_site_banner() as you can see:
add_filter('acf/format_value', 'do_shortcode');
Last but not least I used this CSS for styling the banner and positioned it at the bottom of the page:
.site-banner {
position: fixed;
bottom: 0;
width: 100%;
background-color: #cf2e2e;
padding: 1em;
z-index: 99999;
text-align: center;
color: #ffffff;
}

Related

How to use date and time ACF fields to hide the_content() based on whether time has passed

I am using ACF fields which hold the closing date and closing time.
I have the following variables:
$closing_date = get_field( "closing_date" );
$closing_time = get_field( "closing_time" );
$cdate = $closing_date ." " . $closing_time;
date_default_timezone_set('Africa/Nairobi');
$date2 = new DateTime("$cdate");
Now I need to hide content if time has passed.
The code works well outside a function such as:
if(new DateTime() > $date2)
{?>
<span class="" style="color:white; background:grey; padding:2px; border-radius:2px;">
<?php echo "Closed"; ?></span>
<?php
}
But inside the function it won't work despite declaring the global variables
add_filter('the_content', 'hide_post_contents');
function hide_post_contents( $content ) {
global $date2;
if (new DateTime() > $date2) {
return '<h3>This content is not available </h3>
<p>Please feel free to check out other content.</p>';
}
return $content;
}
However when I add the date manually as below, it works.
add_filter('the_content', 'hide_post_contents');
function hide_post_contents( $content ) {
if (new DateTime() > new DateTime("09-03-2021 15:00")) {
return '<h3>This content is not available </h3>
<p>Please feel free to check out other content.</p>';
}
return $content;
}
Content still displays even when time has passed which is wrong. Cannot get it to work despite several attempts.

How to: Refresh a page between certain times on a day of the week?

I'd like for a web page to automatically refresh between certain times on a specific day of the week (between 9am and 12pm on Wednesdays). New content will be made available on the page, and I want to ensure someone sees the content without having to remember to refresh the page themselves. Not sure how to finish getting this to work. Here's what I have so far:
<?php
$page = $_SERVER['REQUEST_URI'];
$sec = '600000'; // 10 minutes
date("Y-m-d");
date_default_timezone_set('America/Denver');
$time= date('w H:i'); // Day Hour:Minute
if($time >= '3 09:00' && $time <= '3 12:00') { //after 9am and before 12pm on Wednesday
echo '<style type="text/css">.element { display:block; }</style>';
} else {
echo '<style type="text/css">.element { display:none; }</style>';
}
?>
<script type="text/javascript">
setInterval(function() {
window.location.href = '<?php echo $page; ?>';
},<?php echo (int)$sec; ?>);
</script>
Even refreshing just once may be more ideal...
I think that it's better to put your javascript in a php variable ($js).
Better to use setTimeout instead of using setInterval if you want only refresh once.
<?php
$js = '';
$page = $_SERVER['REQUEST_URI'];
$sec = '600000'; // 10 minutes
date("Y-m-d");
date_default_timezone_set('America/Denver');
$time= date('w H:i'); // Day Hour:Minute
if($time >= '3 09:00' && $time <= '3 12:00') { //after 9am and before 12pm on Wednesday
echo '<style type="text/css">.element { display:block; }</style>';
$js = '<script type="text/javascript">setTimeout(function() { location.reload(); }, ".(int)$sec."); </script>';
} else {
echo '<style type="text/css">.element { display:none; }</style>';
}
echo $js;
?>
Tell me if it's what you need.

Creating Store Clock Function - Open/Close & Events depending on time

So I have a code that is functioning properly. I received some help putting this together because despite feeling reasonably confident in my coding skills (fairly new) - time avoids me, I find it confusing to determine how it works in PHP.
I am looking to create a function that acts as my stores clock and returns "open" - "closed" - "1 hour to close" results that I can use in other functions.
For example:
if ( store_clock() == 'open' ) {
echo 'Open';
}
elseif ( store_clock() == '1_hr_left' ) {
echo 'You have 27 mins and 12 secs to place an order' );
else {
echo 'Sorry, we are closed.';
}
I currently have the following code which works correctly in regard to closing times, properly displaying the time left countdown etc. The issue being I don't have my open times, and I would prefer to split the code up - allowing me to use the store_clock() function to trigger other events throughout the site... not just the closing counter.
To do this I am assuming I would need 2 to 3 different functions, rather than just the 1... however I am feeling very confused. Any help appreciated. (PS. get_field() is calling ACF values)
function sat_clock() {
$the_time = current_time('timestamp');
$exact_time = gmdate('g:ia', $the_time);
$weekday_close = get_field('weekday_close', 'options');
$sat_close = get_field('sat_close', 'options');
$sun_close = get_field('sun_close', 'options');
// Set your closing times here from sun-sat
$closing_times = array( $sun_close, $weekday_close, $weekday_close, $weekday_close, $weekday_close, '7:31 pm', $sat_close );
if ( $closing_times[date( 'w', current_time('timestamp') )] !== false ) {
$closing_time = strtotime( sprintf( '%s %s', date( 'd F Y', current_time('timestamp') ), $closing_times[date( 'w', current_time('timestamp') )] ) );
if ( $closing_time - current_time('timestamp') > 0 && $closing_time - current_time('timestamp') < 1800 ) {
echo '<strong>LAST CALL</strong><p class="m-0" id="closing-soon-timer"></p>';
?>
<script>
var timeLeft = <?php echo $closing_time - current_time('timestamp'); ?>;
// Update the count down every 1 second
var x = setInterval(function() {
// Time calculations for minutes and seconds
var minutes = Math.floor(timeLeft / 60);
var seconds = Math.floor(timeLeft % 60);
// Display the result in the element with id="demo"
document.getElementById("closing-soon-timer").innerHTML = "You have <strong>" + minutes + "</strong> minutes " + "<strong>" + seconds + "</strong> seconds to place an order.";
// If the count down is finished, write some text
if (timeLeft < 0) {
clearInterval(x);
document.getElementById("closing-soon-timer").innerHTML = "Closed for today";
}
timeLeft--;
}, 1000);
</script>
<?php
} elseif ( $closing_time - current_time('timestamp') < 0 ) {
echo "<p>Closed for today</p>";
} else {
echo "<p>Opened</p>" . gmdate('g:ia', $closing_time);
var_dump($exact_time);
}
} else {
echo "<p>Closed for today</p>";
}
}
add_action( 'woocommerce_archive_description', 'sat_clock' );

how to filter events with the eventbrite wordpress api

I am creating an event page on wordpress that pulls the eventbrite events data including thumbnails, title, descriptions, cities, etc and since, there are so many events, I would like to add a way to filter the events by which city or which organizer it is from eventbrite with a drop down. I am using https://github.com/Automattic/eventbrite-api for our wordpress site.
This is the work I have done so far and I am stuck.
Also, I am very new to wordpress and php. So everything I have done so far, I am amazed at myself on how I figured it out. I have one more part and I need support.
I figured out that to get organizer, it is get_the_author_meta('ID')) and to get the city is eventbrite_event_venue()->address->city
So what I need support in figuring out is how to get all the cities in a dropdown so when the user selects it. it will be organized by that city. and another drop down when the user select the author, the events only show by that author.
So inside page-events.php
<?php
// Set up and call our Eventbrite query.
$events = new Eventbrite_Query( apply_filters(
'eventbrite_query_args', array(
'display_private' => true, // boolean
'status' => 'live', // string (only available for
display_private true)
'nopaging' => true, // boolean
// 'limit' => 5, // integer
// 'organizer_id' => null, // integer
// 'p' => null, // integer
// 'post__not_in' => null, // array of integers
// 'venue_id' => null, // integer
// 'category_id' => null, // integer
// 'subcategory_id' => null, // integer
// 'format_id' => null, // integer
) ) );
if ( $events->have_posts() ) :
while ( $events->have_posts() ) : $events->the_post(); ?>
<?php get_template_part( 'template-parts/content', 'events' );
?>
<?php endwhile;
// Previous/next post navigation.
eventbrite_paging_nav();
else :
// If no content, include the "No posts found" template.
get_template_part( 'content', 'none' );
endif;
// Return $post to its rightful owner.
wp_reset_postdata();
?>
and inside content-events.php, I have
<article id="event-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="border bg-white clear container box-shadow events-container
mb-4">
<div class="row">
<div class="col-sm-12 col-md-8 p-0 events-image-container">
<img src="<?php echo get_post_thumbnail_id(); ?>"
alt="">
</div>
<div class="col-sm-12 col-md-4 px-4 mt-3">
<p class="m-1 font-weight-bold">
<?php eventbrite_event_organizer(); ?>
<?php
// everything available
foreach((get_the_category()) as
$category) {
echo $category->cat_name . ' ';
}
?>
</p>
<?php eventbrite_event_meta() ?>
</div>
</div>
</div>
for the function eventbrite_event_meta(), I have created
if (!function_exists('eventbrite_event_meta')) {
/**
* Output event information such as date, time, venue, and organizer
*/
function eventbrite_event_meta()
{
// Add a contextual link to event details.
if (eventbrite_is_single()) {
// Link to event info on eventbrite.com.
$url = add_query_arg(array('ref' => 'wporglink'),
eventbrite_event_eb_url());
} else {
// Link to the event single view.
$url = eventbrite_event_eb_url();
}
if (!function_exists('eventbrite_event_time')) {
/**
* Return an event's time.
*
* #return string Event time.
*/
function eventbrite_event_time()
{
// Determine if the end time needs the date included (in the case of multi-day events).
$end_time = eventbrite_is_multiday_event() ? mysql2date('F j Y, g:i A', eventbrite_event_end()->local) : mysql2date('g:i A', eventbrite_event_end()->local);
// Assemble the full event time string.
$event_time = sprintf(_x('%1$s - %2$s', 'Event date and time. %1$s = start time, %2$s = end time', 'eventbrite_api'), esc_html(mysql2date('F j Y, g:i A', eventbrite_event_start()->local)), esc_html($end_time));
return $event_time;
}
}
if (!function_exists('eventbrite_is_multiday_event')) {
/**
* Determine if an event spans multiple calendar days.
*
* #return bool True if start and end date are the same, false otherwise.
*/
function eventbrite_is_multiday_event()
{
// Set date variables for comparison.
$start_date = mysql2date('Ymd', eventbrite_event_start()->utc);
$end_date = mysql2date('Ymd', eventbrite_event_end()->utc);
// Return true if they're different, false otherwise.
return $start_date !== $end_date;
}
}
// Add the organizer's name if available. Author-related functions are filtered to use the event's organizer.
$organizer = '';
if (!empty(eventbrite_event_organizer()->name)) {
$organizer = sprintf('<li class="event-organizer"><span class="screen-reader-text">%s</span><a class="event-organizer-link url fn n" href="%s">%s</a></li>', esc_html__('Organizer', 'writr'), esc_url(eventbrite_event_eb_url(get_the_author_meta('ID'))), esc_html(get_the_author()));
}
// Add a venue name if available.
$venue = '';
if (!empty(eventbrite_event_venue()->address->city)) {
$venue = sprintf('<li class="event-venue"><span class="screen-
reader-text">%s</span><a class="event-venue-link url fn n" href="%s">%s</a> . </li>', esc_html__('Venue', 'writr'), esc_url($url),
esc_html(eventbrite_event_venue()->address->city));
}
apply_filters('eventbrite_event_start', get_post()->start);
// Start with the event time.
$time = sprintf('<li class="event-time"><span class="screen-reader-
text">%s</span><p class="m-0">%s</p></li>', esc_html__('Event date and
time', 'writr'), eventbrite_event_time());
// title of Event
$title_meta = get_the_title();
$title = sprintf( '<li class="entry-title h2 m-0 mb-4 font-weight-
bold">%s</li>',
esc_url($url), esc_html__($title_meta, 'writr'));
// Determine if the end time needs the date included (in the case of
multi-day events).
$event_date_start = eventbrite_is_multiday_event() ? mysql2date('l, F
j', eventbrite_event_start()->local) : mysql2date('l, F j',
eventbrite_event_start()->local);
$event_date = sprintf(_x('<li class="event-time">%1$s</li>', 'Event
date and time. %1$s = start time', 'eventbrite_api'),
esc_html($event_date_start));
// Determine if the end time needs the date included (in the case of
multi-day events).
$event_time_start = eventbrite_is_multiday_event() ? mysql2date('g:iA',
eventbrite_event_start()->local) : mysql2date('g:iA',
eventbrite_event_start()->local);
$event_time_end = eventbrite_is_multiday_event() ? mysql2date('g:iA',
eventbrite_event_end()->local) : mysql2date('g:iA',
eventbrite_event_end()->local);
// Add a venue name if available.
$room = '';
if (!empty(eventbrite_event_venue()->address->address_2)) {
$room = sprintf('<li class="event-venue"><span class="screen-
reader-text">%1$s - %2$s # %3$s</span><a class="event-venue-link url fn n"
href="%4$s">%1$s - %2$s # %3$s</a></li>', esc_html($event_time_start),
esc_html($event_time_end), esc_html(eventbrite_event_venue()->address-
>address_2), esc_url($url));
} else {
// Assemble the full event time string.
$room = sprintf(_x('<li class="event-venue">%1$s - %2$s</li>',
'Event date and time. %1$s = start time, %2$s = end time',
'eventbrite_api'), esc_html($event_time_start),
esc_html($event_time_end));
} ;
$details = sprintf('<li class="event-details mt-2"><a class="event-
details-link btn btn-outline-dark font-weight-bold m-0" role="button"
target="_blank" href="%s">%s</a></li>', esc_url($url),
esc_html__('RSVP', 'writr'));
// Add an event Edit link.
$edit = '';
if (current_user_can('edit_posts')) {
$url = add_query_arg(array('eid' => get_the_ID(), 'ref' =>
'wporgedit'), '<a class="vglnk" href="https://eventbrite.com/edit"
rel="nofollow"><span>https</span><span>://</span><span>eventbrite</span> .
<span>.</span><span>com</span><span>/</span><span>edit</span></a>');
$edit = sprintf('<li class="event-edit">%s</li>',
esc_url($url), esc_html__('Edit', 'writr'));
}
// Assemble our HTML. Yugly.
$html = sprintf('<ul class="clear events-container"><div class="row
header mb-4 text-uppercase"><div class="col-sm-6 p-3 mb-2">%1$s</div>
<div
class="col-sm-6 bg-dark text-white text-center p-3 mb-2">%2$s</div> .
</div>%3$s%4$s%5$s%6$s</ul>', $organizer, $venue, $event_date, $title,
$room, $details);
echo apply_filters('eventbrite_event_meta', $html, $organizer, $venue,
$event_date, $title, $room, $details);
}
}

how to get variable from multipe forms when one of them already submit

I have two form
<form name='theForm' id='theForm' method="post">
and
<form id="frmDate" action="?page=absensi" method="post">
I submit first form with this
<input type="radio" name="keterangan" value="Hadir" onChange="theForm.submit();" />
Second form with this
<script type="text/javascript">
jQuery(function(){
$('#tgl').daterangepicker({
arrows:true,
onChange: function(){
$('#frmDate').submit();
}//removed comma here
});
});
</script>
I already can get variable from one of forms with this
<?php
$keterangan = "";
$date1 = "";
$date2 = "";
if(isset($_POST["keterangan"])){
$keterangan = $_POST["keterangan"];
}
elseif(isset($_POST["tgl"])){
$dates = explode("-",$_POST[tgl] );
$date1= date("Y-m-d", strtotime($dates[0]));
if ($dates[0] == $_POST[tgl]){
$date2 = $date1;
}
else{
$date2= date("Y-m-d", strtotime($dates[1]));}
} ?>
But I don't know how to get variable from forms when one of them already submit.
I have try to manipulate code with this:
<?php
if(isset($_POST["keterangan"])){
$keterangan = $_POST["keterangan"];
if(isset($_POST["tgl"]) and $keterangan<>''){
$dates = explode("-",$_POST[tgl] );
$date1= date("Y-m-d", strtotime($dates[0]));
if ($dates[0] == $_POST[tgl]){
$date2 = $date1;
}
else{
$date2= date("Y-m-d", strtotime($dates[1]));}
}
}
elseif(isset($_POST["tgl"])){
$dates = explode("-",$_POST[tgl] );
$date1= date("Y-m-d", strtotime($dates[0]));
if ($dates[0] == $_POST[tgl]){
$date2 = $date1;
}
else{
$date2= date("Y-m-d", strtotime($dates[1]));}
if(isset($_POST["keterangan"]) and $date1<>'' and $date2<>''){
$keterangan = $_POST["keterangan"];}
} ?>
please help me out from my problem. thanks
Use one form instead of two separated and handle the cases on the backend. You can't read the state of one form if another was submitted.
HTTP is stateless. If you submit a form, you lost the data of the second form.
You must use only one form.

Categories