Display only if a value is set, don't show if empty - php

Just like the title says. I'm trying to only show a line of code on a website if a value is set via a front end panel. The code which I currently have is like this:
For text field input:
<li id="mh-estate_attribute" class="mh-estate__list__element">
<strong>Energieträger:</strong>
<a>
<?php
$terms = get_the_terms( $post->ID, 'energietraeger' );
foreach($terms as $term) {
echo $term->name;
}
?>
</a>
</li>
For number input:
<li id="mh-estate_attribute" class="mh-estate__list__element">
<strong>Baujahr (lt. Energieausweis):</strong>
<?php the_field('estate_attr_' . 'attribute_21', $myhome_estate->get_ID() ); ?>
</li>
So the problem is that an error code is shown on my website when no value is put in.

I'm trying to only show a line of code on a website if a value is set
Try,
if(isset($variable)){
//do what you want to do with not NULL variable
}
OR more specifically
if(!empty($variable){
//do what you want to do with non-empty variable
}

Related

WordPress Advanced Custom Field gallery doesn't return an array

I have ACF Plugin installed and I have a gallery filed in my post. I've tried all these docs but still getting the error :
Invalid argument supplied for `foreach()`
this happens because the input of the for each is not an array!
Do you have any clue what's wrong with this?
Do you think if I have to set something while I've defined the custom field?
<?php
$images = get_field('mygall');
$size = 'full'; // (thumbnail, medium, large, full or custom size)
if( $images ): ?>
<ul>
<?php foreach( $images as $image ): ?>
<li>
<?php echo wp_get_attachment_image( $image['ID'], $size ); ?>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
I think your problem comes from the fact that you are using get_field() instead get_fields(). That's way you don't get an array.
If it still doesn't work check the documentation for get_fields() here. Try to debug it like using only get_fields() and see what is the output. If it is an empty array then it means that you are calling the function out of the loop and it can't get the post id. So do a second test with manually setting the post id like get_fields(123); and check the results. If there are no results then there is something wrong with that post. And if there are results then you can do a final test with checking what will be the result of get_fields(123, 'gallery').
All the above debugging can be wrapped in something like:
echo '<pre>';
print_r( get_fields(123) );
echo '</pre>';
Basically this will give you some idea of what is the structure of the data that you get from this function and how you can manipulate it so to get what you need.

Ghost post_title from my WP LOOP script

The code below is displaying the title in black text before it displays blue title with hyperlink under it.
I only want the link to appear.
if ( $query2->have_posts() ) {
// The 2nd Loop
while ( $query2->have_posts() ) {
$query2->the_post();
if ($post->ID == $do_not_duplicate)
continue;
$permalink = get_the_permalink($query2->post->ID);
$ID = $post->ID;
$titleAtribute = the_title_attribute();
$title = get_the_title();
echo '<h2 id="post-' .$ID.' ">
<a href="'.$permalink.'" rel="bookmark" title="Permanent Link to '.$permalink.' ">
'.$title.'</a></h2>';
}
// Restore original Post Data
wp_reset_postdata();
}
For example, on my website: http://skkelti.cz/, the following text appears in black above the link with the same text:
-Martin Davídek ml. : „Fanoušci jsou vždy to, co vás žene kupředu“-
Where is this coming from and what do I need to do to stop it from appearing?
The problem is with the_title_attribute(). This is displaying the value directly instead of returning it.
The function accepts echo in $args to specify whether to display or return the value. The default value is true (to display it), so pass false to return the value e.g.:
$titleAtribute = the_title_attribute('echo=0');

Display whole fields from group (file + ACF)

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.

Getting first & last post in custom post type outside of loop

I'm using WP, and have a script where when an image is clicked, the single post content loads using .load(). The arrows to navigate through each single post is located inside the .project div that is being loaded using .load().
Problem is, on the first and last posts, I only want to display certain arrows.
For example, the first item in the post gets loaded in, it shouldn't have the 'previous' arrow because there are no previous posts. Same with the last post and the 'next' arrow.
So basically to work around this, I'm trying to come up with a PHP statement (without being in the loop) to tell if the current post is the last post or first post in the custom post type.
Here's what I have so far.. just not sure how to get ID's of first post and last post outside of the loop. Everything else besides that has been tested and works. Below is just the 'logic' behind the code mostly.
<?php
// Get other posts in post type
$next_post = get_next_post();
$previous_post = get_previous_post();
$current_id = get_the_ID();
// Get ID's of posts
$next_id = $next_post->ID;
$previous_id = $previous_post->ID;
// if($next_id == $previous_id) because on first/last posts, get_next_post
// and get_previous_post return the same value.
if($next_id == $previous_id) {
if() {
// if last post in custom post type
} else() {
// if first post in custom post type
}
}
?>
<?php if(isnt first post) { ?>
<li class="left" data-projectid="<?php echo $next_id; ?>"></li>
<?php } ?>
<li class="grid"></li>
<?php if(isnt last post) { ?>
<li class="right" data-projectid="<?php echo $previous_id; ?>"></li>
<?php } ?>
I haven't worked with WP so much, but since WP templates are all PHP files and WP exposes its own API to user you can use any PHP syntax in them. If you're not concerned about running two queries each time you navigate your page then this will help you to get the idea.
<?php
global $wpdb;
$last_one = FALSE;
$first_one = FALSE;
// Get last one
$last_result = $wpdb->get_results("SELECT `id` FROM `posts` ORDER BY `id` DESC LIMIT 0, 1", ARRAY_A);
if($last_result){ if($last_result['id'] == $next_post){ $last_one = TRUE; } }
// Get first one
$first_result = $wpdb->get_results("SELECT `id` FROM `posts` ORDER BY `id` ASC LIMIT 0, 1", ARRAY_A);
if($first_result){ if($first_result['id'] == $previous_post){ $first_one = TRUE; } }
?>
Remember to check the names of fields and tables as I don't know the names.
Ended up using this code and it works fine...
Edit: updated code.. if for any reason somebody else ever needs it:
$args = array('post_type'=>'your_post_type', 'posts_per_page' => -1);
$posts = get_posts($args);
$first_id = $posts[0]->ID; // To get ID of first post in custom post type
// outside of loop
$last_id = end($posts);
echo $last_id->ID; // To get ID of last post in custom post type outside of loop
if($current_id != $first_id) { ?>
<li class="left" data-projectid="<?php echo $previous_id; ?>"></li>
<?php } ?>
<?php if($current_id != $last_id->ID) { ?>
<li class="right" data-projectid="<?php echo $next_id; ?>"></li>
<?php } ?>

How do I get my custom fields to only show when something is written in them - Wordpress?

Im working on customizing a Wordpress theme with some custom fields. For this I'm using the plugin "Advanced Custom Fields", but I want it to display these fields ONLY IF something is written in them. This is the code I'm using to display the custom fields:
<p class="tittelboks">Artikkelforfatter:</p>
<?php if( get_field('artikkelforfatter') )
{
echo '<p>' . get_field('artikkelforfatter') . '</p>';
} ?>
How do I change the code so that it only echos the information AND the label (in this case .tittelboks) if something is written in the meta boxes?
Michael
<?php if( $field = get_field('artikkelforfatter') ): ?>
<p class="tittelboks">Artikkelforfatter:</p>
<p><?php echo $field; ?></p>
<?php endif; ?>
This is a different way of doing an if statement, so you don't have to enclose your HTML in quotes and worry about escaping. The two lines in the middle will only print out if get_field('artikkelforfatter') returns a value or true. That value will be assigned to the $field variable.
Something like this should work:
<?php
$artikkel = get_field( 'artikkelforfatter' );
if ( ! empty( $artikkel ) ) {
?>
<p class="tittelboks">Artikkelforfatter:</p>
<p><?php echo $artikkel; ?></p>
<?php
}
?>
To use and display custom fields need you may try to put this in your loop.
<?php $what_name_you_want=get_post_meta($post->ID,'Your Custom Field Name',true); ?>
<?php echo $what_name_you_want; ?>// This call the value of custom field
Only replace
what_name_you_want with your favorite name
and
Your Custom Field Name with the name of custom field
If the value of custom field is empty the echo will be empty to.
Tell me if it's work

Categories