How to ACF list label not value - php

Im using ACF repeater to generate results form a list, which is all working fine. But, rather than display the list value, I want to display the list label.
Here is the code:
<ul class="notifications-content">
<?php while(has_sub_field('notification')):
$house = get_sub_field('house');
$year = get_sub_field('year');
$date = DateTime::createFromFormat('Ymd', get_sub_field('date'));
$newDate = date("D j F", strtotime($date->format('d-m-Y')));
?>
<li class="<?php echo safe_url($house); ?> <?php echo $year; ?>">
<h2 class="black"><?php echo str_replace($replace, '', get_sub_field('message')); ?></h2>
<h3 class="interstatebold white uppercase"><?php echo $house; echo $year ? ", $year" : ''; echo ' | '.$newDate; ?></h3>
<?php echo get_sub_field('urgent') ? '<div class="circle"></div>' : ''; ?>
</li>
<?php endwhile; ?>
</ul>
How do I get the label?

Take a look at this official documentation about get_field_object
There is a usage example in the bottom:
Get a field object and display it with it's value
$field_name = "text_field";
$field = get_field_object($field_name);
echo $field['label'] . ': ' . $field['value'];
You can use this in your repeater to grab that field_object you want and display the label.

Instead of using has sub field, use get_field('platforms'). Put respective repeater field name in place of 'platforms.' Platforms is the name of repeater field.
By using foreach loop with key=>value pair, you get key as well as value.
Try using following code.
$platforms = get_field('platforms');
foreach( $platforms as $val ){
foreach($val as $key=>$v){
echo $key.'=>'.$v.'<br>';
}
}

You can use it the same way you would call the field values by passing it through these functions (add to functions.php):
function get_field_label($slug) {
$field = get_field_object($slug);
return $field['label'];
}
Usage:
<?php echo get_field_label('field-slug'); ?>
function the_field_label($slug) {
$field = get_field_object($slug);
echo $field['label'];
}
Usage:
<?php the_field_label('field-slug'); ?>

Related

Output All Currency Values using PHP

I am trying to utilize the Bitcoin Charts API to display bitcoin value in all currencies as list items.
Currently I am repeating this PHP snippet in each list item:
<li class="myClass">
<?php
foreach(json_decode(file_get_contents("http://api.bitcoincharts.com/v1/markets.json")) as $item)
if($item->symbol == 'localbtcPLN') break;
printf("\t%s\nPLN", $item->avg);
?>
</li>
How can I simplify this so that the code is only calling the JSON file once?
Thanks for your help.
As per Vishal's assistance, I tried this:
<?php $all_data = json_decode(file_get_contents("http://api.bitcoincharts.com/v1/markets.json"),true);
foreach ($all_data as $data)
{
?><li class="pure-menu-item pure-menu-disabled">
<?php
echo $data['ask'];//use the keyname to get the value
echo ' ';
echo $data['currency'];
?>
</li>
<?php
}
?>
However, it is outputting too much data, including empty values.
Using what I've learned from Florian and Vishal, I have attempted the following snippet, which outputted the data perfectly with the caveat of some duplicated currencies.
<?php $all_data = json_decode(file_get_contents("http://api.bitcoincharts.com/v1/markets.json"),true);
foreach ($all_data as $data)
{
if(trim($data['avg']) != "")//check if value not empty
{
?><li class="pure-menu-item pure-menu-disabled">
<?php
echo $data['avg']; //use the keyname to get the value
echo ' ';
echo $data['currency'];
?>
</li>
<?php
}
}
?>
you can run a foreach loop
<ol>
<?php $all_data = json_decode(file_get_contents("http://api.bitcoincharts.com/v1/markets.json"),true);
foreach ($all_data as $data)
{
if(trim($data['currency']) != "")//check if value not empty
{
?><li>
<?php echo $data['bid'];//use the keyname to get the value ?>
</li>
<?php
}
}
?>
</ol>
I think you want to show values in a certain order.
First, store the result of json_decode() in an array like #Vishal Wadhawan said.
$all_data = json_decode(file_get_contents("http://api.bitcoincharts.com/v1/markets.json"),true);
Next, make a new array where you will store only symbol and avg:
$myvalues = array();
foreach ($all_data as $data)
{
$myvalues[$data['symbol']] = $data['avg'];
}
After that, you can use $myvalues to display avg like that:
<li class="myClass">
<?php echo $myvalues['localbtcPLN'] . ' PLN'; ?>
</li>
You can also store the 'currency' value:
$myvalues[$data['symbol']] = array(
'avg' => $data['avg'],
'currency' => $data['currency'],
);
And access it with:
<li class="myClass">
<?php echo $myvalues['localbtcPLN']['avg'] . ' ' . $myvalues['localbtcPLN']['currency']; ?>
</li>

'echo' a tag without a hyphen and Proper Case using str_replace?

I have a bit of a tricky situation here....
I am pulling bookmarks from a service called Pinboard using their API's which works great - but - the category of the 'tag' (i.e. bookmark tag) is echoed out in full with hyphens.
The difficulty I am having is that I'd like the $tag in one instance to retain the hyphens (to allow for an anchor link using markup to work) - whilst - changing the same $tag that is echoed in the < h1 >
So for example one of the $tag is 'Latest-News' - and I'd like that $tag to be printed like this:
for the anchor tag: $tag will echo 'latest-news'
for the < h1 > tag: $tag will echo 'Latest News'
Any ideas how this is done?
Something like this might be on the right track (I hope! - I'm still clearly a n00b):
$str = str_replace("-", " ", $tag);
echo $tag;
+++++
include 'pinboard-api.php';
$pinboard = new PinboardAPI('myusername', 'xxxxxxx');
$bookmarks_all = $pinboard->get_all();
$bookmarks_grouped_by_tags = array();
foreach ($bookmarks_all as $bookmark) {
if (! empty($bookmark->tags) && is_array($bookmark->tags)) {
foreach ($bookmark->tags as $tag) {
$bookmarks_grouped_by_tags[$tag][] = $bookmark;
}
} else {
$bookmarks_grouped_by_tags['no_tag'][] = $bookmark;
}
}
?>
<?php foreach ($bookmarks_grouped_by_tags as $tag => $bookmarks) { ?>
<a name="<?php echo $tag ?>">
***** <h1><?php echo $tag ?></a></h1> *******
<? foreach ($bookmarks as $bookmark) { ?>
<div>
<?php echo $bookmark->title ?>
</div>
<div><?php echo $bookmark->description ?></div>
<?php } ?>
<?php } ?>
++++

Array an array one minute and not the next? Invalid argument supplied for foreach()

For some reason my code is an array one minute and not the next. I'm just learning php and I can't figure this out. I've used this page to figure most of this out: How to add two Google charts on the one page?
My code is also used on a page that shows the data as a table. On that page it works fine....but for some reason I'm getting Invalid argument supplied for foreach() on the pie charts page...and it's saying it's not an array. I'm not sure how to go about fixing this.
The url I'm using is ?action=scores&data=pie so it should list all of the universities in "get_universities()" (there's 3 there).
Can anyone help please?
The switch:
// Showing scores
case 'scores':
// Grab the Uni ID and use the appropriate query
if (isset($_GET['uni_id']))
{
$uni_id = $_GET['uni_id'];
$uni = get_university($uni_id);
}
else
{
$uni = get_universities();
}
// We have to display this data according to the request
if (isset($_GET['data']))
{
$data = $_GET['data'];
}
else
{
$data = "table";
}
// Display the data accordingly
include (root . '/view/' . $data . '_view.php');
break;
The pie graphs:
// Create the data table.
<?php foreach ($uni as $uni) : ?>
var data<?php echo $uni['university_id']; ?> = new google.visualization.DataTable();
data<?php echo $uni['university_id']; ?>.addColumn('string', 'Area');
data<?php echo $uni['university_id']; ?>.addColumn('number', 'Score');
data<?php echo $uni['university_id']; ?>.addRows([
['Teaching', <?php echo $uni['teaching_score']; ?>],
['Intl Outlook', <?php echo $uni['int_outlook_score']; ?>],
['Industry Income', <?php echo $uni['ind_income_score']; ?>],
['Research', <?php echo $uni['research_score']; ?>],
['Citations', <?php echo $uni['citations_score']; ?>]
]);
<?php endforeach ?>
// Set chart options
<?php foreach ($uni as $uni) : ?>
var options<?php echo $uni['university_id']; ?> = {'title':'<?php echo $uni['university_name']; ?> Scores',
'width':400,
'height':300};
<?php endforeach ?>
// Instantiate and draw our chart, passing in some options.
<?php foreach ($uni as $uni) : ?>
var chart<?php echo $uni['university_id']; ?> = new google.visualization.PieChart(document.getElementById('chart_div<?php echo $uni['university_id']; ?>'));
chart.draw(data<?php echo $uni['university_id']; ?>, options<?php echo $uni['university_id']; ?>);
<?php endforeach ?>
The table view (which works):
<?php foreach ($uni as $uni) : ?>
<td>
<a href="?uni=<?php echo $uni['university_id']; ?>">
<?php echo $uni['university_name']; ?>
</a>
</td>
<etc>
The problem is with your foreach statement:
foreach ($uni as $uni) :
Here you override the $uni variable. Use different names for the collection and item, eg:
foreach ($uni as $theUni) :
// also change instances of $uni below
EDIT
The above is wrong. The parsing of the first parameter of foreach happens only once so in that foreach it won't be a problem. However a foreach is not a new scope, so if you plan to reuse the array variable, you need to choose a different name as the iterator so it won't get overridden.
$a = array(); // $a is array
foreach ($a as $a) {
// $a is element of original $a
}
// $a is the last element of the original $a array
foreach ($a as $a) // Fail, since $a is not an array anymore

How to change loadObjectList() item positions?

I tried to change the positions of the loadObjectList(). but it is not working. can anyone help me to solve this problem?
This is the code i used.
$catID = 8;
//echo $catID;
$doc = JFactory::getDocument();
$page_title = $doc->getTitle();
$db = JFactory::getDBO();
$db->setQuery("SELECT title,alias FROM #__content WHERE catid = ".$catID);
$articles = $db->loadObjectList(); ?>
<div>
<?php foreach($articles as $article){
$title = $article->title;
if($title == $page_title){?>
<h4><?php echo $article->title; ?></h4>
<?php
}else{ ?>
<h4><?php echo $article->title; ?></h4>
<?php }
}
?>
</div>
what i want to do is, i want to display the page title as the first element of the list. Thats means if condition's item should display first.
can anyone helpe me?
A quick dry solution is to add 2 foreach loops and first display the value if condition match and after the rest values.
<?php
foreach($articles as $article){
$title = $article->title;
if($title == $page_title){
echo '<h4>'. $article->title .'</h4>';
}
}
foreach($articles as $rest_articles){
$title = $rest_articles->title;
if($title != $page_title){
echo '<h4>'. $rest_articles->title .'</h4>';
}
}
?>
A better solution is to store values in a new array and display them afterwards.
Hope this helps
Just had a double take here. Multiple foreach loops can be used, however are not required. Try the following:
<?php
foreach($articles as $article) {
$title = $article->title;
$alias = $article->alias;
if($title == $page_title) {
echo '<h4>'. $title .'</h4>';
}
else {
echo '<h4>'. $title .'</h4>';
}
}
?>

Building a html list of links with groups of sublists that are based on a common id

What I have:
I have an array of links and their meta data.
Some links need to be grouped together and some are regular links.
What I'm trying to do:
I'm trying to iterate through my array and group li's with their relative ul, based on a common id.
The problem:
One problem is only making unique ul's based on said id and not make a ul for each item it iterates through.
The second more difficult problem is grouping each item within the relative ul.
Here is an example array I have to work with:
<?php
$array = array();
$array['page']['colours']['link'] = '/colours';
$array['page']['colours']['link-title'] = 'Colours';
$array['page']['colours']['subpage']['green']['aside']['link'] = '/colours/green';
$array['page']['colours']['subpage']['green']['aside']['link-title'] = 'Green';
$array['page']['colours']['subpage']['blue']['aside']['collapse']['id'] = 'cool-colours';
$array['page']['colours']['subpage']['blue']['aside']['link'] = '/colours/blue';
$array['page']['colours']['subpage']['blue']['aside']['link-title'] = 'Blue';
$array['page']['colours']['subpage']['purple']['aside']['collapse']['id'] = 'cool-colours';
$array['page']['colours']['subpage']['purple']['aside']['link'] = '/colours/purple';
$array['page']['colours']['subpage']['purple']['aside']['link-title'] = 'Purple';
$array['page']['colours']['subpage']['orange']['aside']['collapse']['id'] = 'bright-colours';
$array['page']['colours']['subpage']['orange']['aside']['link'] = '/colours/orange';
$array['page']['colours']['subpage']['orange']['aside']['link-title'] = 'Orange';
$array['page']['colours']['subpage']['yellow']['aside']['collapse']['id'] = 'bright-colours';
$array['page']['colours']['subpage']['yellow']['aside']['link'] = '/colours/yellow';
$array['page']['colours']['subpage']['yellow']['aside']['link-title'] = 'Yellow';
$array['page']['colours']['subpage']['red']['aside']['collapse']['id'] = 'bright-colours';
$array['page']['colours']['subpage']['red']['aside']['link'] = '/colours/red';
$array['page']['colours']['subpage']['red']['aside']['link-title'] = 'Red';
$array['page']['colours']['subpage']['pink']['aside']['collapse']['id'] = 'bright-colours';
$array['page']['colours']['subpage']['pink']['aside']['link'] = '/colours/pink';
$array['page']['colours']['subpage']['pink']['aside']['link-title'] = 'Pink';
?>
Here is what I have currently for iterating through this array:
<aside id="sidebar">
<?php
if ( !empty( $array ) ) { ?>
<ul class="menu">
<?php foreach ( $array['page']['colours']['subpage'] as $subpage ) {
if( !empty( $subpage['aside'] ) ) {
$historyArray = array();
?>
<li>
<?php if( !empty( $subpage['aside']['collapse'] ) ) { ?>
<?php if( !in_array( $subpage['aside']['collapse']['id'], $historyArray ) ) { ?>
<a data-toggle="collapse" data-parent="#sidebar" href="#<?php echo $subpage['aside']['collapse']['id'] ?>" class="<?php echo $currentPageLink === $subpage['aside']['link'] ? 'active' : '' ?>"><?php echo $subpage['aside']['link-title'] ?></a>
<ul id="<?php echo $subpage['aside']['collapse']['id'] ?>">
<li>
<?php echo $subpage['aside']['link-title'] ?>
</li>
</ul>
<?php
$historyArray[] = $subpage['aside']['collapse']['id'];
}
?>
<?php } else { ?>
<?php echo $subpage['aside']['link-title'] ?>
<?php } ?>
</li>
<?php } } ?>
</ul>
<?php } ?>
</aside>
Wow, now THAT'S a confusing array! But everything is doable, right? It's just a matter of what you're willing to try. :)
I think you need to create a new array that fits the listing purpose, then iterate through that for the list (The huge complex array will remain intact for whatever else it's used for). Consider this:
<?php
if ( !empty( $array ) ) {
//Create the new array $uls[id][color]['link'/'link-title']
foreach ( $array['page']['colours']['subpage'] as $color => $subpage ) {
$uls[$subpage['aside']['collapse']['id']][$color]['link'] = $subpage['aside']['link'];
$uls[$subpage['aside']['collapse']['id']][$color]['link-title'] = $subpage['aside']['link-title'];
}
}
if ( !empty( $uls ) ) {
echo '<aside id="sidebar">';
echo '<ul class="menu">';
//iterate through the new $uls array
foreach($uls as $id => $color) {
//for each id, we create a ul, then iterate through that id's array
echo '<li><ul id="' . $id . '">';
foreach($color as $link_array) {
//echo the list item for each link in the id
$active = ($currentPageLink === $link_array['link']) ? 'active' : '';
echo '<li>' . $link_array['link-title'] . '</li>';
}
echo '</ul></li>';
}
echo '</ul>';
echo '</aside>';
}
?>
One thing I didn't add was the data-collapse link. I wasn't sure exactly what you were going for there. That shouldn't be too hard to stick in there though.

Categories