Gravity Forms & Advanced Custom Fields - php

I've successfully created the dropdown menu to auto populate the appropriate information from an Advanced Custom Field I created called 'date' on site http://albertson.staging.wpengine.com/seminars/.
Followed along with the instructions here:
http://www.gravityhelp.com/documentation/page/Dynamically_Populating_Drop_Down_Fields
The only issue I'm having is how to display the date in a "pretty" format. You can see that the date is all numbers (20140129) instead of 01/28/2014
To display the date appropriately in the seminar sections above (border red) I use:
<?php if( get_field('date')): ?>
<?php
$date = get_field('date');
// $date = 19881123 (23/11/1988)
// extract Y,M,D
$y = substr($date, 0, 4);
$m = substr($date, 4, 2);
$d = substr($date, 6, 2);
// create UNIX
$time = strtotime("{$d}-{$m}-{$y}");
// format date (November 11th 1988)
echo date('M d', $time);
?>
How do I pass this same information within the Gravity Forms Function I created to get the date to display nicely? Below is my function for Gravity Forms so far.
add_filter('gform_pre_render_4', 'populate_dates');
function populate_dates($form){
foreach($form['fields'] as &$field){
if($field['type'] != 'select' || strpos($field['cssClass'], 'populate-dates') === false)
continue;
// you can add additional parameters here to alter the posts that are retreieved
// more info: http://codex.wordpress.org/Template_Tags/get_posts
$currentdate = date("Y-m-d",mktime(0,0,0,date("m"),date("d"),date("Y")));
$events = get_posts(array(
'post_type' => 'seminars',
'orderby' => 'date',
'order' => 'ASC',
'meta_query'=> array(
array(
'key' => 'date',
'compare' => '>=',
'value' => $currentdate,
'type' => 'DATE',
)),
'meta_key' => 'date',
));
// update 'Select a Post' to whatever you'd like the instructive option to be
$choices = array(array('text' => 'Select a Date', 'value' => ' '));
foreach($events as $post){
$choices[] = array('text' => $post->date, 'value' => $post->date);
}
$field['choices'] = $choices;
}
return $form;
}

Sounds like you're looking for PHP's date function. We convert the date string to a timestamp via strtotime() and then use date() to format the date as you wish.
$formatted_date = date( 'm/d/Y', strtotime( $post->date ) );
In your code example:
foreach( $events as $post ){
$formatted_date = date( 'm/d/Y', strtotime( $post->date ) );
$choices[] = array('text' => $formatted_date, 'value' => $post->date );
}

Related

Count Posts Between Dates

I use a few ACF date fields to basically provide start and end dates for posts, I need to be able to display how many posts are starting in the current month and ending in the current month, this is what I have so far, this doesn't provide the accurate count, not sure what's wrong with this and if it could be simplified. I have confirmed the function portion below is working correctly.
function getBetweenDates($startDate, $endDate) //array of dates for current month
{
$rangArray = [];
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
for ($currentDate = $startDate; $currentDate <= $endDate;
$currentDate += (86400)) {
$date = date('Y-m-d', $currentDate);
$rangArray[] = $date;
}
return $rangArray;
}
$this_month = getBetweenDates(date("Y-m-01"), date("Y-m-t"));
$posts = get_posts(array(//start dates this month
'post_type' => 'project',
'meta_key' => 'landlord_delivery_date',
'meta_value' => $this_month,
'meta_compare' => 'IN',
));
$fpposts = get_posts(array(//end dates this month
'post_type' => 'project',
'meta_key' => 'first_patient_date',
'meta_value' => $this_month,
'meta_compare' => 'IN',
));
$count = count($posts);//count ll dates
$fpcount = count($fpposts);//count fp dates```

Convert ISOdate to phpdate for ACF custom field query

I've built a custom beaver builder (wordpress) module. I'm fetching posts via Ajax. I need to query posts based off an ACF custom field date.
I am posting the date in ISO8601 format (eg 2013-12-01T00:00:00-05:00). Server side, I grab the start and end. I convert them into the format needed for the ACF query https://www.advancedcustomfields.com/resources/date-picker/
$start_date = date('Ymd', strtotime($_POST['start']));
$end_date = date('Ymd', strtotime($_POST['end']));
I run the query, and get nothing. I echo the string out, and they look correct.
If I set the date as per the example in the ACF docs - it works (code below). So I must be converting the ISOdate $_POST['start'] incorrectly. How do I convert the ISODATE so that is it something that I can use in the query?
function get_ajax_event_calendar_posts() {
$today = date('Ymd'); // this works...
$args = array(
'post_type' => array('event'),
'meta_query' => array(
array(
'key' => 'start_date',
'compare' => '<=',
'value' => $today,
),
array(
'key' => 'end_date',
'compare' => '>=',
'value' => $today,
)
),
'post_status' => array('publish'),
'posts_per_page' => 100,
'nopaging' => true,
'order' => 'DESC',
'orderby' => 'date'
);
// The Query
$ajaxposts = get_posts( $args );
//... etc
}
** edit **
.... the date stuff wasn't the problem. I was the problem... switched my compares round the right way and all works...
You haven't said what format you actually need to store the data, however you did say date('Ymd') works. Either way, use the DateTime class:
<?php
$x = new DateTime('2013-12-01T00:00:00-05:00');
echo $x->format('d/m/Y H:i:s') . "\n"; // 01/12/2013 00:00:00
echo $x->format('dmY') . "\n"; // 01122013
Here are the date formats https://www.php.net/manual/en/function.date.php

Can't get globals variable to work, how to pass the value from template to function in functions.php

Edited:
Problem is that when doing ajax loading of more posts the $year1 or $year value gets repeated. The value of $year is actually a month.
How it looks now:
December
Event 1
November
Event 2
Event 3
November--- here the ajax call happens and the month value gets repeated
Event 4
Event 5
Event 6
and How it should be:
December
Event 1
November
Event 2
Event 3
Event 4
Event 5
Event 6
I have so far tried with globals variables
Get a variable from one wordpress template file to another
and get query variables
https://wordpress.stackexchange.com/questions/96312/get-query-var-vs-global-query-variables
Another problem is that the date in functions.php returns the values in english, while the same code returns the date in spanish
in the template.
Code in template: Do note I used the $test variable with November value for testing porpuses, but it should be $year1
I don't know what I am doing wrong...
$my_posts = new WP_Query( $args );
if ( $my_posts->have_posts() ) :
?>
<div class="my-posts2">
<?php while ( $my_posts->have_posts() ) : $my_posts->the_post() ?>
<?php
$dateformatstring = 'F';
$unixtimestamp = strtotime(get_field('start_date'));
$year1 = date_i18n($dateformatstring, $unixtimestamp);
$year_check2 = $GLOBALS['year_checkbarcelonafunctions'];
// If your year hasn't been echoed earlier in the loop, echo it now
if (($year1 !== $year_check1) && ($year1 !== $year_check2)){
echo "<h2 class='year-act text-center'>" . $year1 . "</h2>";
}
// Now that your year has been printed, assign it to the $year_check variable
$test = 'November';
$GLOBALS['year_checkbarcelona1'] = $test;
$year_check1 = $year1;
?>
Code in functions.php:
function load_posts_by_ajax_callback2() {
check_ajax_referer('load_more_posts2', 'security2');
$paged = $_POST['page'];
$today = current_time('Y-m-d');
$args = array (
'meta_query' => array(
'relation' => 'AND',
array(
'category' => 'actividades',
'key' => 'start_date',
'value' => $today,
'compare' => '<',
'type' => 'DATE',
),
array(
'key' => 'region',
'value' => 'Barcelona',
'compare' => '='
),
),
'meta_key' => 'start_date',
'orderby' => 'meta_value',
'order' => 'DSC',
'posts_per_page' => 3,
'paged' => $paged,
);
$query = new WP_Query( $args ); ?>
<?php if ( $query->have_posts() ) : ?>
<?php while ( $query->have_posts() ) : $query->the_post();?>
<?php
$dateformatstring = 'F';
$unixtimestamp = strtotime(get_field('start_date'));
$year = date_i18n($dateformatstring, $unixtimestamp);
//Example another global
//$paged = $_POST['page'];
$year_check1 = $GLOBALS['year_checkbarcelona1'];
// If your year hasn't been echoed earlier in the loop, echo it now
if (($year !== $year_check) && ($year !== $year_check1)){
echo "<h2 class='year-act text-center'>" . $year . "</h2>";
}
// Now that your year has been printed, assign it to the $year_check variable
$GLOBALS['year_checkbarcelonafunctions'] = $year;
$year_check = $year;
?>
So in other words, the global values should avoid duplicating the $year tag that groups the activities/events when doing ajax loading.
Edit: I'm open to other solutions that don't rely on globals.
Edit3: I'm using this code (that is not working) inside the loop of the events template:
global $mytest2;
$mytest2 = 'November';
and in the functions.php inside the function load_posts_by_ajax_callback2, I have tried with
ob_start();
global $mytest2;
echo $mytest2;
$myStr = ob_get_contents();
ob_end_clean();
if (($year !== $year_check) && ($year !== $myStr)){
echo "<h2 class='year-act text-center'>" . $year . "</h2>";
}

Filter Gravity Forms Entries By Date

I am trying to filter (show) Gravity Forms Entries on the front end of my site between two certain dates. One being today (the current present date) and a custom date added within the backend of the website.
So only entries that were submitted between the custom date and the present date.
I have two variables storing these dates:
$new_start_date is the custom date, and
$end_date is the present days' date.
My code is outputting 200 entries but some of which are before the custom start date.
Below is my query code:
<?php
//Get the Form ID to get the entries from and store it within a varibale
$form_id = GFAPI::get_form(2);
// Get Dates
$date_page_id = get_field( 'update_dates_page_link', 'options', false, false );
$start_date = get_field( 'oak_submission_date', $date_page_id ); // date of the last submission date
$end_date = date( 'Y-m-d', time() ); //get today's date
// Convert start_date to match end_date format
$new_start_date = DateTime::createFromFormat( 'd/m/Y', $start_date );
$new_start_date = $new_start_date->format( 'Y-m-d' );
$search_criteria = array(
'status' => 'active',
'start_date' => $new_start_date,
'end_date' => $end_date,
'field_filters' => array(
array(
'key' => '53', // Trust name field
'value' => 'Oak Trust',
),
array(
'key' => '49', // Grant Made field
'value' => 'No',
),
),
);
$sorting = null;
$paging = array( 'offset' => 0, 'page_size' => 200 );
$entries = GFAPI::get_entries( $form_id, $search_criteria, $sorting, $paging );
// Code that outputs to the screen
foreach ( $entries as $entry) :
echo '<li>';
echo 'ID: '. $entry[68] .' : ' . $entry[2] .' : Submission Date: '. $entry[54];
echo '</li>';
endforeach;
GFAPI::get_form(2) doesn't return the Form ID it returns the Form. Try this:
$entries = GFAPI::get_entries( 2, $search_criteria, $sorting, $paging );

WordPress running two queries together

This is an events website that handles the location of each event relative to the users location and displays the distance in search results.
I'm using the WP GeoQuery extension to allow me to query based on distance. However, it doesn't work well with things like tax_query. So, I'm wondering if there's a way of running the WP_GeoQuery to query for events within a certain distance, then run the result of that through the normal Wp_Query to get it to filter for the correct taxonomies and other arguments?
Here's the Geo Query:
$url = "http://freegeoip.net/json/". $_SERVER['REMOTE_ADDR'] .'';
$geo = json_decode(file_get_contents($url), true);
$geo_query = new WP_GeoQuery(array(
// location stuff
'latitude' => $geo[latitude], // User's Latitude (optional)
'longitude' => $geo[longitude], // User's Longitude (optional)
// radius breaks the query if using tax_query too
'radius' => 25 // Radius to select for in miles (optional)
));
And here's the normal WP_Query:
// add query for title
function title_filter( $where, &$wp_query ) {
global $wpdb;
if ( $search_term = $wp_query->get( 'title_like' ) ) {
$where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( like_escape( $search_term ) ) . '%\'';
}
return $where;
}
add_filter( 'posts_where', 'title_filter', 10, 2 );
// dates to and from
function date_from( $from ) {
$from = str_replace("meta_key = 'date_%_start-date'", "meta_key LIKE 'date_%_start-date'", $from);
return $from;
}
add_filter('posts_where', 'date_from');
function date_to( $to ) {
$to = str_replace("mt1.meta_key = 'date_%_end-date'", "mt1.meta_key LIKE 'date_%_end-date'", $to);
return $to;
}
add_filter('posts_where', 'date_to');
// convert date to yyyymmdd
$date1 = str_replace('/', '-', $_POST['when']);
$when = date("Ymd", strtotime($date1));
$date2 = str_replace('/', '-', $_POST['when-2']);
$when2 = date("Ymd", strtotime($date2));
?>
<h1>Search</h1>
<div class="events">
<?php $args = array(
// general
'post_type' => 'event',
'post_status' => 'publish',
'posts_per_page' => 2,
'paged' => $paged,
// what input
'title_like' => $_POST['what'],
// category filter
'tax_query' => array(
array(
'taxonomy' => 'main-cat',
'field' => 'slug',
'terms' => $_POST['main-cat']
)
),
// date filter
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'date_%_start-date',
'value' => $when,
'compare' => '>=',
'type' => 'DATE'
),
array (
'key' => 'date_%_end-date',
'value' => $when2,
'compare' => '<=',
'type' => 'DATE'
)
),
);
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query( $args );
$wp_query->query('posts_per_page=2&post_type=event'.'&paged='.$paged);
When used individually they work fine. But I'm not sure how I can run one of them, then use the result to put through the other query. Is this even possible?

Categories