I'm creating a timeline using timesheet.js. The data will be input via custom fields in Wordpress. I want to be able to output that php data into the jquery array. Is that possible?
This is my php loop:
<?php if( have_rows('timeline') ):
while ( have_rows('timeline') ) : the_row();
echo the_sub_field('start_date');
echo the_sub_field('end_date');
echo the_sub_field('description');
echo the_sub_field('name');
endwhile;
endif; ?>
Here's the jquery, each time the php loops through I want it to output in the format:
<script type="text/javascript">
jQuery(function($) {
$(document).ready(function() {
new Timesheet('timesheet', 2002, 2013, [
['2002', '09/2002', 'A freaking awesome time', 'lorem'],
['06/2002', '09/2003', 'Some great memories', 'ipsum'],
['2003', 'Had very bad luck'],
['10/2003', '2006', 'At least had fun', 'dolor'],
['02/2005', '05/2006', 'Enjoyed those times as well', 'ipsum'],
['07/2005', '09/2005', 'Bad luck again', 'default'],
['10/2005', '2008', 'For a long time nothing happened', 'dolor'],
['01/2008', '05/2009', 'LOST Season #4', 'lorem'],
['01/2009', '05/2009', 'LOST Season #4', 'lorem'],
['02/2010', '05/2010', 'LOST Season #5', 'lorem'],
['09/2008', '06/2010', 'FRINGE #1 & #2', 'ipsum']
]);
});
});
</script>
It's quite simple to do this, really: just construct the array in php, and echo its json_encoded value:
<?php
$array = array();
if( have_rows('timeline') ) {
while ( have_rows('timeline') ) : the_row();
$array[] = array(
the_sub_field('start_date'),
the_sub_field('end_date'),
the_sub_field('description'),
the_sub_field('name')
);
endwhile;
echo '<script> var theArray = '.json_encode($array).';</script>';
} ?>
Job done, you now have a JS variable called theArray, and its value will be an array of arrays, containing all of the data you need to create new Timesheet('timesheet', 2002, 2013, theArray);
Yes, you need to echo <script> tags and you can generate any Javascript you want:
<?php
echo '<script>';
if( have_rows('timeline') ):
echo 'var foo = ['
while ( have_rows('timeline') ) : the_row();
echo '"'.the_sub_field('start_date').'",';
echo '"'.the_sub_field('end_date').'",';
echo '"'.the_sub_field('description').'",';
echo '"'.the_sub_field('name').'"';
endwhile;
echo '];';
endif;
echo '</script>';
?>
Related
I am running a loop that will pick up any news items that should appear in a corner pop up on a website. I have the popup working great for the first item, but the second doesn't show. I've tried to do it by calling the function twice with a different delay & timeout on each one, so they should appear in sequence. I don't really do much jquery/javascript, so I don't understand why that doesn't work. I am guessing it is because the function is the same? Can anyone help me out? Code below!
TIA
<?php $delay = 50;
$timeout = 3000;
$i = 1;
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php if (have_rows('home_page_pop_up')) :
while(have_rows('home_page_pop_up')) : the_row();
if (get_sub_field('show_home') == 'Yes') :
$showdate = get_sub_field('until_date');
$today = date('Ymd');
if ( $today <= $showdate ):
?>
<script>
jQuery.fn.cornerpopup({
variant: 9,
//displayOnce: true,
slide: true,
timeOut: <?php echo $timeout; ?>,
delay: <?php echo $delay; ?>,
link2: "<?php echo site_url(); ?>/news-community/",
header: "Recent News",
text2: "<h5><?php the_title(); ?></h5><p><?php the_excerpt(); ?> ... <a href='<?php the_permalink(); ?>'>Read more</a></p>",
button3: "View all News",
stickToBottom: true,
});
</script>
<?php endif;
endif;
$i++;
$delay = $delay + 3000;
$timeout = $timeout + 3000;
endwhile;
endif;
endwhile;
?>
i use a google charts for getting data from google analytics to see it in my website
there is some data have a decimal number
how to make the charts forgot the number after the decimal.
I use a php foreach in the data generate for the charts
like this:
var data = google.visualization.arrayToDataTable([
['WEEK', 'total Cost' ,{ role: 'annotation' } ],
<? foreach($SOMETHING->getRows() as $row) {
$test = $row[2];
$test = number_format($test,0);?>
["<? echo $row[0]; ?>", <? echo $row[2]; ?>, <? echo $test; ?> ],
<? }?>
]);
i try the php coding "number_format" but it working in the script if i see the inspect of the page but not showing any charts in the page
if i put this code it work but the decimal is still there
var data = google.visualization.arrayToDataTable([
['WEEK', 'total Cost' ,{ role: 'annotation' } ],
<? foreach($tristanweekdata->getRows() as $row) { ?>
["<? echo $row[0]; ?>", <? echo $row[2]; ?>, <? echo $row[2]; ?> ],
<? }?>
]);
P.S.: this code is for one of my charts but its effect all the charts and all of them not showing anything
what should i do for remove the decimal????
thanks
Wrap your value in PHP's floor or intval method: (using number_format as you have it will add commas at the thousandths place in your numbers, so that should be avoided).
echo floor(456.8)."<br/>";
echo floor(456)."<br/>";
echo floor(456.1)."<br/>";
echo floor(456.0);
// outputs:
// 456
// 456
// 456
// 456
echo intval(456.8)."<br/>";
echo intval(456)."<br/>";
echo intval(456.1)."<br/>";
echo intval(456.0);
// outputs:
// 456
// 456
// 456
// 456
So in your example above:
$test = floor($row[2]);
//or
$test = intval($row[2]);
Floor:
Returns the next lowest integer value
http://php.net/manual/en/function.floor.php
Intval
Returns the integer value of var, using the specified base for the conversion (the default is base 10)
http://php.net/manual/en/function.intval.php
So my website lists upcoming film screenings in my area.
I'm using the ACF date time picker to only show posts/film screenings that are in the future in the wordpress loop.
I have tags filtering the results dynamically using ajax (thanks to https://www.bobz.co/ajax-filter-posts-tag/) except there are tags that aren't relevant to the results because they belong to posts that are older than the current date (past screenings).
*For example on the website, the 'animated film festival' is still coming up with the other tags.
I don't know if it's possible to delete a posts tags with PHP (within the post template while it loops through other posts) - and to delete the posts tags if the ACF date time field for that post is older than the current date.
I haven't found much luck googling this and I am a bit of a noob so...
This is my site: http://pigcine.pamrosel.com/
This is what I'm doing in my functions.php file at the moment:
// Get all tags and display
function tags_filter() {
$tax = 'post_tag';
$terms = get_terms( $tax );
$count = count( $terms );
if ( $count > 0 ): ?>
<div class="post-tags">
<?php
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, $tax );
echo '' . $term->name . ' ';
} ?>
</div>
<?php endif; }
// Script for getting posts
function ajax_filter_get_posts( $taxonomy ) {
// Verify nonce
if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce($_POST['afp_nonce'], 'afp_nonce' ) )
die('Permission denied');
$taxonomy = $_POST['taxonomy'];
// WP Query
$args = array(
'tag' => $taxonomy,
'post_type' => 'post',
'posts_per_page' => -1,
'meta_key' => 'datetime',
'orderby' => array(
'datetime' => 'ASC'
),
);
// If taxonomy is not set, remove key from array and get all posts
if( !$taxonomy ) {
unset( $args['tag'] );
}
$query = new WP_Query( $args );
if ( $query->have_posts() ) : while($query->have_posts()) : $query>the_post();
$today = date('Y-m-d H:i:s', strtotime('+9 hours'));
$event_date = get_field('datetime');
if (strtotime($today) <= strtotime($event_date)) {
?>
<div class="sl">
<div class="sl_closed">
<div class="col-2-8"><div class="modulepad">
<p><?php the_field('datetime'); ?></p>
</div></div>
<div class="col-3-8"><div class="modulepad">
<p><?php the_title(); ?><br>
<?php $wpmovieinput = get_field('movie_title'); $movie = imdb_connector_get_movie($wpmovieinput); echo implode(", ", $movie["directors"]); ?>
</p>
</div></div>
<div class="col-3-8"><div class="modulepad">
<p><?php the_field('location_name'); ?><br>
<?php $wpmovieinput = get_field('movie_title'); $movie = imdb_connector_get_movie($wpmovieinput); echo implode(", ", $movie["countries"]) . " "; echo $movie["released"] . " "; echo implode(", ", $movie["runtime"]); ?>
</p>
</div></div>
</div><!--SL_CLOSED-->
<?php } endwhile; ?>
<?php else: ?>
<h2>No posts found</h2>
<?php endif;
die();
}
add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');
I am building a statistical view for a client's booking system. They'd like to see which activities were booked in specific months.
I'm using Google Charts for this but the data doesn't match the labels being produced - i.e. the correct data is being attached to the wrong activity.
I've verified via the database and print_r's that the product IDs are being pulled from the database successfully and attached to the correct activity ID number, and that the number and order of labels matches the number and order of activities, which they are:
$sql = "SELECT ProductID, ProductName FROM products ORDER BY ProductID ASC";
$set = $link->query($sql);
while($row = $set->fetch_row())
{
$arrLabels[$row[0]] = "#".$row[0].": ".$row[1];
}
ksort($arrLabels);
$sql = "SELECT * FROM bookings_products INNER JOIN bookings ON bookings.BookingID=bookings_products.BookingProductBooking WHERE BookingConfirmed>0 ORDER BY BookingProductProduct ASC";
$set = $link->query($sql);
while($row = $set->fetch_array(MYSQLI_ASSOC))
{
$dm = substr($row['BookingDate'],5,2); // To get the month from YYYY-MM-DD dates
$arrPeople[$dm][$row['BookingProductProduct']] = $arrPeople[$dm][$row['BookingProductProduct']] + (1 * $row['BookingGroupSize']);
}
ksort($arrPeople);
echo "<pre>"; print_r($arrLabels); echo "</pre>";
echo "<hr/>";
echo "<pre>"; print_r($arrPeople); echo "</pre>";
I then build the Google Charts JS code like this:
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var data = google.visualization.arrayToDataTable([
[<?php foreach($arrLabels as $p) { ?>'<?php echo str_replace("'","\'",$p); ?>', <?php } ?>{ role: 'annotation' } ],
['Jan', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['01'][$k] ?: '0'; ?>, <?php } ?>],
['Feb', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['02'][$k] ?: '0'; ?>, <?php } ?>],
['Mar', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['03'][$k] ?: '0'; ?>, <?php } ?>],
['Apr', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['04'][$k] ?: '0'; ?>, <?php } ?>],
['May', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['05'][$k] ?: '0'; ?>, <?php } ?>],
['Jun', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['06'][$k] ?: '0'; ?>, <?php } ?>],
['Jul', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['07'][$k] ?: '0'; ?>, <?php } ?>],
['Aug', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['08'][$k] ?: '0'; ?>, <?php } ?>],
['Sep', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['09'][$k] ?: '0'; ?>, <?php } ?>],
['Oct', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['10'][$k] ?: '0'; ?>, <?php } ?>],
['Nov', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['11'][$k] ?: '0'; ?>, <?php } ?>],
['Dec', <?php foreach($arrLabels as $k=>$v) { ?><?php echo $arrPeople['12'][$k] ?: '0'; ?>, <?php } ?>],
]);
var options = {
title: 'Product popularity by month - Number of people (based on activity date)',
isStacked: true,
};
var chart = new google.visualization.BarChart(document.getElementById('chart3b'));
chart.draw(data, options);
}
</script>
<div id="chart3b" style="margin-top:15px; width: 900px; height: 500px; border:solid 1px #000;"></div><hr/>
You can see (via a static HTML copy-and-paste of the dynamic PHP output) the Google Chart produced here: http://www.stuart-pinfold.co.uk/stats.htm
You'll notice that activity #50 (Santa Experience) which had 195 visitors in December (month 12) is being assigned in the chart to activity #51 ("Zombie Air Rifle, Zombie Pistol, 10 Clay Shoots") instead.
Where am I going wrong?
Your first column of values is the month name, but your first cell at your headers row isn't a "month" label.
If you look at your example the activity #50 (Santa experience), you can see that the value of this label is 1 step to the left in the graph.
Make sure that instead of
['#5: Special Offer Ultimate Shooting Package ', '#6: CPSA Shotgun Skills Course',.....],
['Jan', 0,....
it looks like
['Months', '#5: Special Offer Ultimate Shooting Package ',.....],
['Jan', 0,.....
and everything should work just fine.
I have the following php code that gives an array variable called "markers".
window.markers = [];
<?php if( have_rows('actin_center') ): ?>
<?php while( have_rows('actin_center') ): the_row(); ?>
window.markers.push( [ ['<?php the_sub_field('center_name'); ?>', '<?php the_sub_field('center_address'); ?>', <?php the_sub_field('latitude'); ?>, <?php the_sub_field('longitude'); ?>] ] );
<?php endwhile; ?>
<?php endif; ?>
This works fine so far yet returns the array (on alert) as:
Cool center 1,Rewitz Gofella, 1234 Lorem,50,50,Cool center 2,Lorem Ipsum, 1234 Quosque,60,60,Cool center 3,Veniat elaborat, 1234 Ipsum,70,70
What I need, yet, is the following form keeping the arrays (of sub_fields) as they originally are inside the array and NOT concatenate them. As:
var markers = [
['First Center','First Address',50,50],
['Second Center','Second Address', -25.363882,131.044922],
['Third Center','Third Address', 10.363882,95],
['Fourth Center','Fourth Address', -50,-90],
['Fifth Center','Fifth Address', 30,5],
];
As you can see in the code above I tried with the simple double bracket [[ ]] but this doesn’t work.
How is this to be done correctly?
Thanks so much for help.
PS:
If someone feels urged to down vote my question, please be so kind to let me know why so I may learn something.
Due to comments:
alert( [[1,2][3,4]] ) will popup wrong 1,2,3,4
alert( JSON.stringify([[1,2][3,4]]) will popup [[1,2],[3,4]]
.push([1,2]) will add an array to markers: [[1,2],[3,4],[5,6]]
.push(1,2) will add elements to markers: [1,2,3,4,5,6]
But better way, is don't execute javascript .push (save client CPU time)
Define array in javascript in this way:
window.markers = [
<?php while( have_rows('actin_center') ): the_row(); ?>
["<?php the_sub_field('center_name');?>","<?php the_sub_field('center_address'); ?>",<?php the_sub_field('latitude');?>, <?php the_sub_field('longitude');?>],
<?php endwhile; ?>
];
result should looks like this
window.markers = [
['First Center', 'First Address', 50, 50],
['Second Center','Second Address',-25.363882, 131.044922],
[... ,... , ... ,...],
];