How to Remove Trailing Comma [duplicate] - php

This question already has answers here:
How to create a JSON object
(5 answers)
Closed 9 months ago.
I am trying to remove the trailing comma from my php statement
<?php foreach( $speaker_posts as $sp ): ?>
{
"#type" : "person",
"name" : "<?php the_field('name_title', $sp->ID); ?>",
"sameAs" : "<?php echo post_permalink( $sp->ID ); ?>"
},
<?php endforeach; ?>

Assuming your array is well formed (has indexes starting from zero) you can put it at the beginning, skipping the first record:
<?php foreach( $speaker_posts as $idx => $sp ): ?>
<?php if ($idx) echo ","; ?>
{
"#type" : "person",
"name" : "<?php the_field('name_title', $sp->ID); ?>",
"sameAs" : "<?php echo post_permalink( $sp->ID ); ?>"
}
<?php endforeach; ?>
Otherwise you need an external counter:
<?php $idx = 0; foreach( $speaker_posts as $sp ): ?>
<?php if ($idx++) echo ","; ?>
{
"#type" : "person",
"name" : "<?php the_field('name_title', $sp->ID); ?>",
"sameAs" : "<?php echo post_permalink( $sp->ID ); ?>"
}
<?php endforeach; ?>

Since you're apparently outputting JSON, use PHP to do it.
<?php
$json = [];
foreach($speaker_posts as $sp) {
$json[] = [
'#type' => 'person',
'name' => get_field('name_title', $sp->ID),
'sameAs' => post_permalink( $sp->ID ),
];
}
print json_encode($json);
?>
Side note: this will save you from potentially unsafe characters like quotation marks / apostrophes in the field/permalink contents.

Related

How to Google Tag Manager DataLayer in Wordpress PHP Function

I've been trying to figure out how to make a dataLayer for the Order Confirmation page (Thankyou.php). I wanted to add the following function (via functions.php or Code Snippet) but it gives a fatal error when I try. Can anyone see what I'm doing wrong or if there is a better way to do this?
I'm fairly new but trying to learn and I've been researching but can't find the answer, sorry if this may be a novice question. It gives a fatal error for the < in script so I thought maybe I wasn't supposed to have in PHP but when I remove that then I get a fatal error for unexpected { on same line:
add_action( 'woocommerce_thankyou', 'checkout_datalayer' );
function checkout_datalayer( $order_id ) {
<script>
dataLayer.push({
'ecommerce': {
'currencyCode': '<?php echo $order->get_order_currency(); ?>',
'purchase': {
'actionField':{
'id': '<?php echo $order->get_order_number(); ?>',
'affiliation': 'Website',
'revenue': <?php echo number_format($order->get_total(), 2, ".", ""); ?>,
'shipping': <?php echo number_format($order->calculate_shipping(), 2, ".", ""); ?>,
<?php if($order->get_used_coupons()): ?>
'coupon': '<?php echo implode("-", $order->get_used_coupons()); ?>'
<?php endif; ?>
},
'products': [
<?php
foreach($order->get_items() as $key => $item):
$product = $order->get_product_from_item( $item );
?>
{
'name': '<?php echo $item['name']; ?>',
'id': '<?php echo $product->get_sku(); ?>',
'price': '<?php echo number_format($order->get_line_subtotal($item), 2, ".", ""); ?>',
'brand': 'Brand',
'quantity': <?php echo $item['qty']; ?>
},
<?php endforeach; ?>
]
}
}
});
</script>
}
To anyone interested, I figured out the issue I believe. It was assuming the entire thing was PHP and the only way to stop that was to add ?> before the <script> and <?php after the </script>.

Correctly Passing data from Controller to View CodeIgniter

This question may be asked numerous times but I am facing difficulty in doing so.
var_dump($lex_post_data); works fine on controller
My Controller code
try{
// need for the manage functionality to be initialized.
$manage_mode = FALSE;
$appointment = array();
$provider = array();
$customer = array();
$lex_post_data = $this->input->post('lexname');
var_dump($lex_post_data);
// Load the book appointment view.
$view = array (
'available_services' => $available_services,
'available_providers' => $available_providers,
'company_name' => $company_name,
'manage_mode' => $manage_mode,
'appointment_data' => $appointment,
'provider_data' => $provider,
'customer_data' => $customer,
'post_data' => $lex_post_data
);
} catch(Exception $exc) {
$view['exceptions'][] = $exc;
}
$this->load->view('appointments/book', $view);
View Code:
<script type="text/javascript">
var GlobalVariables = {
availableServices : <?php echo json_encode($available_services); ?>,
availableProviders : <?php echo json_encode($available_providers); ?>,
baseUrl : <?php echo '"' . $this->config->item('base_url') . '"'; ?>,
manageMode : <?php echo ($manage_mode) ? 'true' : 'false'; ?>,
appointmentData : <?php echo json_encode($appointment_data); ?>,
providerData : <?php echo json_encode($provider_data); ?>,
customerData : <?php echo json_encode($customer_data); ?>,
lexpostData : <?php echo json_encode($lex_post_data); ?>,
csrfToken : <?php echo json_encode($this->security->get_csrf_hash()); ?>
};
console.log(GlobalVariables);
var EALang = <?php echo json_encode($this->lang->language); ?>;
var availableLanguages = <?php echo json_encode($this->config->item('available_languages')); ?>;
$(document).ready(function() {
FrontendBook.initialize(true, GlobalVariables.manageMode);
// GeneralFunctions.centerElementOnPage($('#book-appointment-wizard'));
GeneralFunctions.enableLanguageSelection($('#select-language'));
});
</script>
Ques1: Is this the correct way of accessing the values sent from controller.
Ques2: On console.log(GlobalVariables); I am getting
lexpostData : null
What I am doing wrong.
Please guide
EDIT
SOLVED & CLOSED: I was trying to get differnt name varriable on view. Had to use
lexpostData : <?php echo json_encode($post_data); ?>,
instead of
lexpostData : <?php echo json_encode($lex_post_data); ?>,
In controller you are passing $lex_post_data in post_data
'post_data' => $lex_post_data
So in view instead of
<?php echo json_encode($lex_post_data); ?>
Use
<?php echo json_encode($post_data); ?>

Is there a better way of exploding the comma maybe from the last item in the foreach statement?

I have used the Google visulization plugin for displaying charts, because it is dynamically pulled in from a database I have used the following foreach script to display the results:
var chartData = {
dynamic: [
['Date', 'Orders'],
<?php foreach($data['orders-by-date'] as $date => $orderCount): ?>
['<?php echo date('d/m', $date); ?>', <?php echo $orderCount; ?>],
<?php endforeach; ?>
[' ',0] /* Fix for IE8 */
]
};
As you can see I have to add a fix in for IE8 as the last one has to have the comma removed or it breaks in IE8.
Is there a better way of exploding the comma maybe from the last item in the foreach statement? My way works but it adds on a blank value to the end of the chart which isn't ideal.
I hope this makes sense!
I tried the following but doesn't seem to work:
<script type="text/javascript">
var chartData = {
dynamic: [
['Date', 'Orders'],
<?php $fCnt = count($data); ?>
<?php foreach($data['orders-by-date'] as $date => $orderCount): ?>
['<?php echo date('d/m', $date); ?>', <?php echo $orderCount; ?>],
<?php ($date != $fCnt - 1 ? ',' : ''); ?>
<?php endforeach; ?>
]
};
</script>
var chartData = {
dynamic: [
['Date', 'Orders'],
<?php
$last = end($data['orders-by-date']);
foreach($data['orders-by-date'] as $date => $orderCount): ?>
['<?php echo date('d/m', $date); ?>', <?php echo $orderCount; ?>]<?php echo ($date != $last) ? ',' : ''; ?>
<?php endforeach; ?>
]
};
Try this:
var chartData = {
dynamic: [
<?php
$data = array();
$data[0] = ['Date', 'Orders'];
foreach($data['orders-by-date'] as $date => $orderCount)
{
$data[]="[".date('d/m', $date).",".$orderCount."]";
}
echo implode(",",$data);
?>
]
};

Filtering HTML for javascript output

I'm using the prettyPhoto API to open the the lightbox manually with the following code:
api_images ['images/fullscreen/image1.jpg','images/fullscreen/image2.jpg','images/fullscreen/image3.jpg'];
api_titles = ['Title 1','Title 2','Title 3'];
api_descriptions = ['Description 1','Description 2','Description 3']
$.prettyPhoto.open(api_images,api_titles,api_descriptions);
The problem i'm facing is that the description values are pulling from Wordpress's WYSIWYG and the code is easily broken with random html tags, punctuation etc
<script type="text/javascript">
$(document).ready(function() {
$('#menu-item-1006').on('click', function(e) {
e.preventDefault();
var images = new Array();
var descriptions = new Array();
var titles = new Array();
<?php
$i = 0;
$images = new WP_Query(array('post_type' => 'clearance', 'showposts' => -1, 'order' => 'menu_order', 'orderby' => 'ASC'));
if ($images->have_posts()) : while ($images->have_posts()) : $images->the_post();
$featured = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full');
?>
images[<?php echo $i; ?>] = '<?php echo $featured[0]; ?>';
titles[<?php echo $i; ?>] = '<?php the_title(); ?>'
descriptions[<?php echo $i; ?>] = '<?php echo get_the_content(); ?>';
<?php
$i++;
endwhile;
else:
?>
<?php endif; ?>
$.prettyPhoto.open(images, titles, descriptions);
})
});
</script>
How can i filter the get_the_content() function so it will output w/o errors? Thanks!
a simple solution could be:
replace
<?php echo get_the_content(); ?>
with
<?php echo preg_replace('/\<[^\>]+\>/s', '', get_the_content()); ?>
json_encode(get_the_content()) works!
$content = get_the_content();
echo strip_tags($content, '<a><img>');
will leave only a and img tags. I think it's all what you need for gallery

JSON error passing html

I have problem with JSON, passing html code, I don't understand because I escaped with addslashes php function.
This is the JSON that fail:
With php JSON is valid:
<?php if(count($articles)): ?>
{"items":[
<?php foreach($articles as $key => $article): ?>
<?php if($key==0 ):?>
{
"foto_g": "<?php echo $article->getRutafoto() ?>",
"foto_th": "<?php echo $article->getRutathumb() ?>"
}
<?php else: ?>
,
{
"foto_g": "<?php echo $article->getRutafoto() ?>",
"foto_th": "<?php echo $article->getRutathumb() ?>"
}
<?php endif ?>
<?php endforeach ?>
],
"nom_coleccio": "<?php echo $coleccio->getNom()?>"
,
"descripcio_coleccio": "<?php echo addslashes($coleccio->getDescripcio(ESC_RAW))?>"
}
<?php endif ?>
And the result that have problem is:
{
"descripcio_coleccio": "<p>El delta de l\'Ebre ha estat l\'escenari d\'inspiració d\'aquesta col·lecció.</p>
<p>La línia de l\'horitzó i el color del paisatge materialitzats en alumini s\'uneixen per a crear volum en forma de joia.</p>"
}
When is the problem?
Thanks Regards
You should use proper encoding functions if possible. In case of JSON you should use json_encode, even if just for particular values.
But it would be easier if you collect the values in an array with associative keys and use json_encode only at the end:
if (count($articles)) {
$items = array();
foreach ($articles as $key => $article) {
$items[] = array(
"foto_g" => $article->getRutafoto(),
"foto_th" => $article->getRutathumb()
}
}
$data = array(
"items" => $items,
"nom_coleccio" => $coleccio->getNom(),
"descripcio_coleccio" => $coleccio->getDescripcio(ESC_RAW)
);
echo json_encode($data);
}
Don't do that! Construct the JSON properly in PHP instead:
<?php
echo json_encode(array
(
"descripcio_coleccio" => $coleccio->getDescripcio(ESC_RAW)
));
?>
Those single quotes shouldn't be escaped:
{
"descripcio_coleccio": "<p>Eldeltadel'Ebrehaestatl'escenarid'inspiraciód'aquestacol·lecció.</p><p>Lalíniadel'horitzóielcolordelpaisatgematerialitzatsenaluminis'uneixenperacrearvolumenformadejoia.</p>"
}

Categories