I made the ACF plugin group with files to download. In group I have fields "File 1", "File 2"...etc.
I would like to display all attached files to page. It is possible to display all fields belong to group? I try with basic code, but in this case I have only 1 file.
How can I add iteration to this or display all fields?
<?php
$file = get_field('attachment_1');
if( $file ):
// vars
$url = $file['url'];
$title = $file['title'];
$caption = $file['caption'];
if( $caption ): ?>
<div class="wp-caption">
<?php endif; ?>
<ul>
<li><a href="<?php echo $url; ?>" title="<?php echo $title; ?>">
<span><?php echo $title; ?></span>
</a>
</li>
<ul>
<?php if( $caption ): ?>
<p class="wp-caption-text"><?php echo $caption; ?></p>
</div>
<?php endif; ?>
<?php endif; ?>
As all your fields are set up individually, it isn't just a matter of looping through an array of all your fields of the same type (i.e. just your file fields).
There are a few ways that might work for you:
Option 1.
If all the field names for your files follow the same naming pattern and are named sequentially, you could loop using the name.
Example, assuming your fields are named attachment_1 up to attachment_5:
$statement = get_field('name_of_your_statement_field');
//do whatever you need to with $statement
for ($i=1; $i<=5; $i++){
//use the number from the loop to find the file by name
$file = get_field('attachment_'.$i);
if( $file ){
// display file details as appropriate
}
}
Option 2.
If the file field names do not follow the same pattern, you could loop through an array of the field names.
Example:
$statement = get_field('name_of_your_statement_field');
//do whatever you need to with $statement
// Create an array with the field names of all your files
// N.B. This also lets you specify the order to process them
$file_fieldnames = array('file_1', 'file2', 'another_file');
foreach ($file_fieldnames as $fieldname) {
$file = get_field($fieldname);
if( $file ){
// display file details as appropriate
}
}
Option 3. If you want to loop through ALL fields on the post/page, you can save the fields into an array.
This might seem like the most generic approach at first, but it is complicated by the fact that you don't know what type each field is in order to know how to process and display them... you first have to work out what field type it is. You could do this by name (similar to above) or you could try to identify what each field by checking the field content.
Note, checking the field content is very risky, as there are other field types that can have similar featured (e.g. a file is not the only type that can have a url) so I wouldn't advise that strategy unless you are 100% sure you'll never change the field group or add another field group to the post/page.
Example:
$fields = get_fields();
foreach ($fields as $fieldname => $content) {
if (is_string ($content)){
// display the string
}
else if (is_array($content) && $content['url']) {
// then you could assume its a file and display as appropriate
}
}
Note that none of this code is tested. However it should give you an idea of the logic behind each option so you can decide what works for you.
UPDATE based on new code provided:
See below based on the code in your JSFiddle. I've ignored the caption outside the file list because it makes no sense - every file can have its own caption.
<?php
for ($i=1; $i<=5; $i++){
//use the number from the loop to find the file by name
$file = get_field('attachment_'.$i);
if( $file ){
$url = $file['url'];
$title = $file['title'];
$caption = $file['caption'];
// now display this file INSIDE the loop so that each one gets displayed:
?>
<li>
<a href="<?php echo $url; ?>" title="<?php echo $title; ?>" target="_blank">
<span><?php echo $title; ?></span>
</a>
<?php if( $caption ): ?>
<p class="wp-caption-text"><?php echo $caption; ?></p>
<?php endif; ?>
</li>
<?php
} // end if
} // end for loop
?>
<ul>
If you understand arrays, I'd suggest you add the file details into an array and then do a second loop to display the files... however I'm guessing you're not that proficient with basic coding constructs as you don't understand loops, so I've tried to keep it simple. I strongly recommend that you do some tutorials on programming basics if you are attempting to write code.
Related
I'm trying to make a fun side project and have come to a stop on a small problem. I am trying to have the echo command placed inside of the while and mysqli_fetch_assoc command as the data changes everytime the page refreshes, from the select from table random function.
I select random items like this:
$survivor_set = random_survivor();
$item_set = random_item();
$firstaidkitaddon_set = random_firstaidkitaddon();
$flashlightaddon_set = random_flashlightaddon();
$keyaddon_set = random_keyaddon();
$mapaddon_set = random_mapaddon();
$toolboxaddon_set = random_toolboxaddon();
$survivoroffering_set = random_survivoroffering();
The problem line of code looks like this:
<?php while($toolboxaddon = mysqli_fetch_assoc($toolboxaddon_set)) { ?>
However I need the words after $ to be changed so was looking for something like this to work:
<?php while($ echo h($item['item']);addon = mysqli_fetch_assoc($ echo h($item['type']);addon_set)) { ?>
This is probably explained poorly, I would appreciate if anyone could lend some time to help me where I can show in more details what exactly I am trying to accomplish.
The code shows the random item that was selected from the table.
<?php while($item = mysqli_fetch_assoc($item_set)) { ?>
<?php echo h($item['name']);?> E.g. Engineers Toolbox
<?php echo h($item['rarity']);?> E.g. veryrare
<?php echo h($item['type']);?> E.g. toolbox
<?php echo h($item['media']);?> E.g. engineerstoolbox.png
<?php } ?>
I am then trying to find a way to put the echo h($item['type']) into the next output. so it would look like this when it is a toolbox.
<?php while($toolbox = mysqli_fetch_assoc($toolbox_set)) { ?>
But then could change due to it being a different item type that was pulled:
<?php while($flashlight = mysqli_fetch_assoc($flashlight_set)) { ?>
Full code, for context: https://zerobin.net/?9f772676aa87df3f#Gxy43WGqShTkL/VG42+t3nT4+sxGhxFy+GDB0B3+YH0=
You should store all your different add-on results in an associative array where the keys match the possible "type" values from your main item query. This allows you to select an item from the array using a string to reference its key - and you can take that string value from your $item['type'] variable.
e.g.
$survivor_set = random_survivor();
$item_set = random_item();
$addons = array(
"firstaid" => random_firstaidkitaddon(),
"flashlight" => = random_flashlightaddon(),
"key" = random_keyaddon(),
"map" = random_mapaddon(),
"toolbox" => random_toolboxaddon()
);
$survivoroffering_set = random_survivoroffering();
Then later on you can select the right set of results from the associative array by selecting the index which matches $item['type']:
<div class="itemaddonscontainer">
<div class="<?php echo h($item['type']);?>">
<?php while($addon = mysqli_fetch_assoc($addons[$item['type']])) { ?>
<img class="<?php echo h($addon['rarity']);?> survivor-item" src="imgs/survivor/itemaddon/<?php echo h($addon['media']);?>"/>
<?php } ?>
</div>
</div>
N.B. mysqli_free_result probably isn't necessary here.
I'm pretty new in PHP and what I would like to do is for PHP to check if a certain image file with a specific name exists in a specific directory, then echo the name of the file, but if it doesn't exist, then just show XXX.png.
I currently have a page (http://powerplantv2.jehzlau.net/ppm-deals) that echoes all product names from a certain attribute in Magento.
This page calls all images based on the attribute name. For example in my page there's an attribute name called "cool haan". So it automatically calls the image named "coolhaan.png". If there's an attribute name called "levis" then it will show an image named levis.png.
But I don't know how to add a condition if levis.png doesn't exist in the directory, I just want to call XXX.png.
How can I let PHP check first if the image exists that matches the certain attribute in the directory, then show attributename.png, if now, XXX.png.
Currently, below is my code:
<?php
$name ='deals';
$attributeInfo = Mage::getResourceModel('eav/entity_attribute_collection')->setCodeFilter($name)->getFirstItem(); $attributeId = $attributeInfo->getAttributeId();
$attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attributeId); $ppmtenants =
$attribute ->getSource()->getAllOptions(false); ?>
<?php foreach ($ppmtenants as $ppmtenant): ?>
<img src="<?php echo $this->getUrl() ?>media/wysiwyg/Deals/<?php echo strtolower($ppmtenantclean); ?>.png">
<?php endforeach; ?>
The code above gets all the options from a certain attribute then displays all the images with the attribute name. What I want to do is to check for the image name first before showing it.
To simplify my question, I just want to add a placeholder image with the name XXX.png for attributes with no images yet. :D
You can use file_exists() http://php.net/manual/en/function.file-exists.php to check if the file exists and then display the image, otherwise output the placeholder image.
<?php if(file_exists(path_to_your_file)) {
// Image does exist, fetch the image
} else {
// Image doesn't exist, output xxx.png
}
?>
Both the answers posted so far are correct, but to make things easier for you, you can do something like this:
<?php foreach ($ppmtenants as $ppmtenant):
if(file_exists($this->getUrl()."media/wysiwyg/Deals/".strtolower($ppmtenantclean).".png"))
{ ?>
<img src="<?php echo $this->getUrl() ?>media/wysiwyg/Deals/<?php echo strtolower($ppmtenantclean); ?>.png">
<?php
}
else
{
echo '<img src="xxx.png" alt="No image" />';
}
?>
<?php endforeach; ?>
<?php
if (!file_exists("PATH_TO_IMAGE") {
//display xxx.png
} else {
//load the image
}
Making mobile site with Concrete5 and using page list block with custom template. I'm trying to count sub pages using PHP.
<?php foreach ($pages as $page):
// Prepare data for each page being listed...
$title = $th->entities($page->getCollectionName());
$url = $nh->getLinkToCollection($page);
$target = ($page->getCollectionPointerExternalLink() != '' && $page->openCollectionPointerExternalLinkInNewWindow()) ? '_blank' : $page->getAttribute('nav_target');
$target = empty($target) ? '_self' : $target;
$description = $page->getCollectionDescription();
$description = $controller->truncateSummaries ? $th->shorten($description, $controller->truncateChars) : $description;
$description = $th->entities($description);
$mies = 0;
?>
<li class="ui-btn ui-btn-icon-right ui-li-has-arrow ui-li ui-btn-up-c" data-theme="c"><div aria-hidden="true" class="ui-btn-inner ui-li"><div class="ui-btn-text"><a target="<?php echo $target ?>" class="ui-link-inherit" href="<?php echo $url ?>">
<h2 class="ui-li-heading"><?php echo $title ?></h2>
<p class="ui-li-desc"><?php echo $description ?></p>
</a>
</div><span class="ui-icon ui-icon-arrow-r ui-icon-shadow"></span><span class="ul-li-count ui-btn-corner-all ul-count-second"><?php echo count($mies) ?></span></div></li>
<?php endforeach; ?>
So, probably need to use Count function(or length?), I don't know. If I am editing wrong place please advice if you have any experience in Concrete5 cms.
If you want to show the corresponding page number in the span element in your code:
<span class="ul-li-count ui-btn-corner-all ul-count-second"><?php echo $mies; ?></span>
If you want to show the remaining sub-pages, then in the html code snippet above just replace $mies with count($pages) - $mies like:
<span class="ul-li-count ui-btn-corner-all ul-count-second"><?php echo count($pages) -$mies; ?></span>
You would first have to initialise $mies before you start the forloop so it should be something of the form:
<?php
$mies = 0;
foreach ($pages as $page):
//Rest of your code and increment $mies with every iteration
$mies ++; //This ensures that you are counting the corresponding pages
?>
If you want to get the count of total number of sub-pages, you just have to echo out $mies outside the for block may be like:
<?php
endforeach;
echo $mies; //Shows you the total number of pages processed inside the for loop.
//or Just find the length of pages array
echo count($pages);
?>
As far as getting the length of array is concerned you could use count or sizeof. I stumbled upon a SO question about using count or sizeof method for finding the length of an array.
This should get you started in the right direction.
You need the parent ID;
$parentId = Page::getCollectionParentId();
Note that Page::getCollectionParentId() gets the current page's parent ID,so you may want to try;
$parentId = $page->getCollectionParentID();
Then create a new PageList to filter with and filter by the parentId;
Loader::model('page_list');
$pl = new PageList();
$pl->filter(false, '(p1.cParentID IN ' . $parentId . ')');
// Get the total
var_dump($pl->getTotal());
This is untested but the theory makes sense.
This is likely a bit simpler.
$pl->getTotal()
$pl is the PageList object that is set in the controller.
Also, these days you can just use the h() method instead of writing out $th->entities()
Edit: I should clarify that you don't need to do a $pl = new PageList() because $pl is already set to the PageList object in the controller and passed to the view.
So I'm wanting to make a way to display the 2nd newest row from my database. So my example (To help better explain it) If i have 10 rows. I want to display only the second newest one. Not the newest one but the one right after it. Or the maybe even the third one. I have my working code below and i see the for each loop. But I'm not sure how to only display the one I'm wanting it to display. I also don't think how i have it set up is the most efficient way of acomplishing this.
I am using concrete5 for this site and the main idea is for composer so i can post a new post and the pull a recent news feed but showing the second post.
Here is my current code: (This shows the first post)
<?php
defined('C5_EXECUTE') or die("Access Denied.");
?>
<div id="blog-index">
<?php
$isFirst = true; //So first item in list can have a different css class (e.g. no top border)
$excerptBlocks = ($controller->truncateSummaries ? 1 : null); //1 is the number of blocks to include in the excerpt
$truncateChars = ($controller->truncateSummaries ? $controller->truncateChars : 255);
$imgHelper = Loader::Helper('image');
foreach ($cArray as $cobj):
$title = $cobj->getCollectionName();
$date = $cobj->getCollectionDatePublic(DATE_APP_GENERIC_MDY_FULL);
$author = $cobj->getVersionObject()->getVersionAuthorUserName();
$link = $nh->getLinkToCollection($cobj);
$firstClass = $isFirst ? 'first-entry' : '';
$entryController = Loader::controller($cobj);
if(method_exists($entryController,'getCommentCountString')) {
$comments = $entryController->getCommentCountString('%s '.t('Comment'), '%s '.t('Comments'));
}
$isFirst = false;
?>
<div class="entry">
<div class="title">
<h3>
<?php echo $title; ?>
</h3>
<h6 class="post-date">
<?php
echo t('Posted by %s on %s',$author,$date);
?>
</h6>
</div>
<div class="excerpt">
<?php
$a = new Area('Main');
$a->disableControls();
if($truncateChars) {
$th = Loader::helper('text');
ob_start();
$a->display($cobj);
$excerpt = ob_get_clean();
echo $th->entities($th->shorten($excerpt,$truncateChars));
} else {
$a->display($cobj);
}
?>
</div>
<div class="ccm-spacer"></div>
<br />
<div class="meta">
<?php echo $comments; ?> <?php echo t('Read the full post'); ?> <i class="icon-chevron-right"></i>
</div>
</div>
<hr class="blog-entry-divider"/>
<?php endforeach; ?>
</div>
To build upon what the others have written as comments:
What you've pasted is a concrete5 view. You'll notice there's no db querying or PageList building in there. For that, you need to look in the controller. (This looks like a page list block view, so the controller will be in / concrete / core / controllers / blocks / page_list.php (on c5.6+).
The concrete5 api code to do what the others have suggested (let mysql handle the skipping) is done within the ->get() call. So, on about line 135:
$pl->get(1, 1);
Remember not to modify the files directly, but to override them the c5 way. There are plenty of tutorials on this on the c5 website.
I'm using Views 3 in Drupal 7 to output a list of fields and using a grouping field to generate separate lists. I need each of the groupings to have a unique ID attribute applied to the < ul > but they don't by default.
As far as I'm aware I would need to edit the views-view-list.tpl.php template but I don't know how to achieve a unique ID per iteration.
Can anyone help please?
easiest way I can think of off the top of my head...
<?php print $wrapper_prefix; ?>
<?php if (!empty($title)) : ?>
<h3><?php print $title; ?></h3>
<?php endif; ?>
<ul id="<?php echo uniqid(); ?>">
<?php foreach ($rows as $id => $row): ?>
<li class="<?php print $classes_array[$id]; ?>"><?php print $row; ?></li>
<?php endforeach; ?>
</ul>
<?php print $wrapper_suffix; ?>
that would go in your views-view-list.tpl.php file.
For future reference:
Put a div around everyting in view-views-list.tpl.php. You can (ab-)use the $title to generate unique (but consistent) id's.
Do it like this:
<?php $id = str_replace('FOR ALL UNWANTED CHARS','',$title); ?>
<div id="<?php print strtolower($id); ?>">
You can use the $view->dom_id variable. It is a unique id for that views instance.
In your .tpl.php file:
<?php print $view->dom_id; ?>
From comments in modules\views\theme\theme.inc:
<?php
// It is true that the DIV wrapper has classes denoting the name of the view
// and its display ID, but this is not enough to unequivocally match a view
// with its HTML, because one view may appear several times on the page. So
// we set up a hash with the current time, $dom_id, to issue a "unique" identifier for
// each view. This identifier is written to both Drupal.settings and the DIV
// wrapper.
?>