PHP, Advanced Custom Fields, Wordpress, if statement - php

What am I doing wrong? Just to warn you this is my first attempt at php so pardon my ignorance ;)
Currently using Wordpress with a plugin called Advanced Custom Fields. Which allows you to create custom field options in the backend of wordpress.
http://plugins.elliotcondon.com/advanced-custom-fields/
I am trying to get a div to hide if the value of the Advanced Custom Field "Available" (which is a select list) is set to "No". The div is a marker for the 10 available apartments that overlays a map. Currently it displays all 10 markers whether it's availability is set to "No" or "Yes".
$i = 201;
$available = get_field('available');
while ($i <= 210) :
if ($available == 'No') {
echo '<div id="apt-' . $i . '" class="map-marker" style="display:none;"></div>';
} elseif ($available) {
echo '<div id="apt-' . $i . '" class="map-marker">';
echo $i++;
echo'</div>';
}
endwhile;

what are you trying to accomplish here? the get_field function is a per post in the loop method, so you would need to be iterating over the whole posts collection with the
while ($loop->have_posts()) : $loop->the_post();
if you're not using a custom loop you would leave off the $loop-> part.
you probably need to post the whole page template. you might just need to do some studying on wordpress about the loop and how it works.

Related

How to get the image links from Gutenberg block gallery and add them as html data attributes to a button in wordpress

I'm using gutenberg gallery block inside a post and I'm trying to create a button which contains all of the image ids in the gallery block as html data attributes such that later when I output the content to the page I can have access to those ids using javascript. Basically I'm trying to create a lightbox feature for a custom post type.
The problem is that I can't get access to the gutenberg gallery block data.
Here's my code
while ($custom_post_type->have_posts()) {
$custom_post_type->the_post();
$gallery = get_post_gallery(get_the_id(), false);
$ids = explode(",", $gallery['ids']);
}
And here's that button with html data attributes
<button class="gallery"
<?php
for ($i = 0; $i < count($ids); $i++) {
$img_link = wp_get_attachment_image_url($ids[$i], 'full');
echo "data-img-" . $i . " = " . $img_link . " ";
}?>
>
Light-box
</button>
But it does not work, $ids is empty. It prints out this
<button class="gallery">Light-box</button>
Thanks for your help!
Edit
I'm using wordpress blocks on the post page, I'm not quite certain how they have been generated, but they work out of the box.
"it does not work, $ids is empty."
That block is one of the default wordpress blocks, aka "core blocks". In order to have access to its data you would need to use parse_blocks function not get_post_gallery. That's why your variable is empty.
So the overall workflow to get what you're looking for would be:
Check whether your post has any blocks or not, using has_block function. has_blockDocs
If it does, then get all of the blocks (including gallery block) using parse_blocks function. parse_blocksDocs
parse_blocks will return an array of all blocks used in your post, so loop through them and see which one is called "core/gallery".
"core/gallery" block has "attributes" and "ids" for each image you've added in the admin panel.
Once you get the "ids", you should be able to create your custom button and image links using wp_get_attachment_image_url function. wp_get_attachment_image_urlDocs
As a POC:
Please see the following code:
if (has_block("gallery", get_the_content()))
{
$post_blocks = parse_blocks(get_the_content());
foreach ($post_blocks as $post_block)
{
if ("core/gallery" == $post_block["blockName"])
{
$ids = $post_block["attrs"]["ids"];
}
}
}
And this is the button:
<button class="gallery"
<?php
for ($i = 0; $i < count($ids); $i++) {
$img_link = wp_get_attachment_image_url($ids[$i], "full");
echo "data-img-" . $i . " = " . $img_link . " ";
}
?>
>
Light Box
</button>
Which will return:
Note:
I've used get_the_content function, assuming that you're in the loop based on the code you provided in your question. If you're not in the loop or you would need to use the code outside of the loop you could use global $post; $post->post_content; instead.
This answer has been tested on wordpress 5.8 and works.

ACF Repeater field [shortcode] - do not show anything if subfields are empty

I am trying to create a TO DO list with ACF Advanced Custom Fields in Wordpress.
What I want to achieve is a shortcode that will display the TO DO repeater wrapped in Div tags with H3 title.
But IF the sub-fields are empty, nothing should show up, not even the H3 title.
I got as far as this:
add_shortcode( 'TO-DO-LIST', 'my-to-do-list');
function my-to-do-list($atts){
if(!function_exists('get_field'))
return;
ob_start();
// check if the repeater field has rows of data
if( have_rows('acf_to_do_repeater_group') ):
echo '<div id="to-do-list-wrapper">';
echo '<h3>TO DO:</h3>';
echo '<div class="to-do-content-wrapper">';
echo '<ul class="to-do-list-wrap">';
?>
<?php
// loop through the rows of data
while ( have_rows('acf_to_do_repeater_group') ) : the_row();
// display a sub field value
$content = get_sub_field('to-do-repeater-subfield');
echo '<li>' . $content . '</li>';
endwhile;
echo '</ul></div></div>';
endif;
$output = ob_get_clean();
return $output;
}
It works for getting the values, so if the rows have input, everything shows up correctly, however I can't seem to be able to figure out how to hide the entire thing when the rows are empty.
Currently even if the rows are empty, it still shows the list.
What am I doing wrong here?
Add a count on the have rows function: if its returning a empty set for some reason for 0, you can increase the count to 1.
if( have_rows('acf_to_do_repeater_group') && count(have_rows('acf_to_do_repeater_group')) > 0):

Wordpress how to insert multiple CSS via custom field

I am struggling with custom field to insert page specific CSS or JS in Wordpress.
I was able to insert single CSS following the article.
http://www.wpbeginner.com/wp-themes/embed-custom-css-in-your-single-posts-with-custom-fields/
Then I was wondering what if I want to insert multiple CSSs via a custom field.
I guess I have to do with Arrays and loops, right?
Can I just want put multiple CSSs in one field by separating with commas or something?
Example:
in the custom field section:
field name: customCSS
filed value: foo.css, bar.css, other.css ...
Could someone give me an idea how to do it?
Thank you.
My wordpress ver. is 3.8.
I found a solution to this. basic PHP stuff...
I dont know if this is efficient, but I got what I want as a result.
I used comma(,) as a delimiter in the custom field.
if (is_page()) {
$uniqueCSS = get_post_meta($post->ID, uniqueCSS ,true);
$uniqueCSSArr = explode(',', $uniqueCSS);
if($uniqueCSSArr) {
for( $i = 0; $i < count($uniqueCSSArr); $i++ ) {
echo '<link rel="stylesheet" href="'. get_template_directory_uri() .'/css/'. $uniqueCSSArr[$i] .'"/>';
echo "\n";
}
}
}
Thank you

Wordpress meta tag challenge

I'm currently trying to create a site for TV shows and due to certain wordpress limitations this is becoming a challenge.
However I bypass that with the use of implementing custom meta fields in the functions.php file, now my problem is that I need it to actively create new fields when I submit information in the current field. For example custom metabox names are
(Episode Name="This is It") (Episode Number="1") (Season Number="5")
Instead of having to create all the boxes from the beginning I would like the use Javascript (jQuery) or any solution to automatically create a new set of these 3 boxes
(Episode Name="") (Episode Number="") (Season Number="")
so I can just enter the new information as they come. Thank you in advance for your help!
Note: I have invested too much time into wordpress to just switch to another cms, so that is not an option at this point in time.
from what I understand of your question, you are looking for a simple solution to automate the input process. I have a general idea of what it is you nee to achieve as I have had to do something similar on a brochure type of website.
I have tried answering your question using Jquery, but I find it to increase the amount of text input required when creating your post, there is unfortunately no completely automated method of doing it, but hopefully below would provide you with a solution.
first I found the following plugin: Types - Complete Solution for Custom Fields and Types here: http://wordpress.org/extend/plugins/types/
This allows you to create custom meta feilds when creating a new post/page. The custom feilds are brought added with a perfix of "wpcf-" and then the name of the field, e.g. "Episode Name" becomes "wpcf-episode-name" in the database.
The following is an edit of wordpress's get_meta function:
function get_specifications(){
if ( $keys = get_post_custom_keys() ) {
echo '<div class="entry_specifications">';
foreach ( (array) $keys as $key ) {
$keyt = trim($key);
if ( '_' == $keyt[0] )
continue;
$values = array_map('trim', get_post_custom_values($key));
$value = implode($values,', ');
//remove "wpcf-"
$key = str_replace('wpcf-','',$key);
//convert "-" to a space " "
$key = str_replace('-',' ',$key);
//check if it has a value, continue if it does, skip if it doesn't:
if ($value <> ''){
echo apply_filters('the_meta_key', "
<div class='meta_wrapper'>
<div class='meta_title'>$key</div>
<div class='meta_value'>$value</div>
</div>\n", $key, $value);
};
}
}
// echo '</div>'; comment out and remove the line below if you are not using floats in your css
echo '</div><div class="clear"></div>';
}
In my page.php (or your template-page.php) I have added the following code when/where I want the meta to be produced:
<?php
//check to see if there is meta data, as you only want the meta data on TV Program pages
$met_check = get_post_meta($post->ID, 'wpcf-features', true);
if ($met_check <> ''){
//if it has a value, spit out "About EpisodeName" ?>
<h2 class="post-title clear">About <?php echo $title ?></h2>
<?php //perform the function from functions.php and return results:
echo get_specifications();
}
?>
I've styled the result with the following CSS:
.meta_entry {
clear:both;
}
.meta_title {
float:left;
text-transform:capitalize;
width:200px;
}
.meta_value {
float:left;
width:480px;
}
Hope this helps mate!
There is a wonderful plugin for wordpress called Pods which might be a viable solution.
Try http://wordpress.org/extend/plugins/custom-field-template/

How to create permalinks without single pages in wordpress?

I'm creating my own wordpress theme which is a bit different because it will not have single pages (or atleast, no single page will be reachable). The whole website contains just the homepage (with the loop) and previous posts pages.
I want to link to individual posts inside the loop like site.com#post-124 or site.com/paged=5#post-214.
I already created a function that does this:
function getPermalink($id,$postsPerPage) {
$postNumber = Get_Post_Number($id);
//a function that get's the post number based on
//the chronical order of published posts.
$page = floor(($postNumber - 1) / $postsPerPage);
$url = get_option('home');
if($page > 0) {
$url .= '/?paged=' . ($page + (1 - floor($page / 5)));
}
$url .= '#post-' . $id;
return $url;
}
You can see it live here: http://mijnrealiteit.nl (the previous posts pages are replaced by an infite scroll plugin).
This works, however it breaks when I start adding posts because all the posts before will get shifted back to pages further away (this makes the link invalid).
The way I see it there are two possible solutions:
Change the permalinkstructure to display paging backwards (so x.com/paged=231 becomes the first 'previous' page. However this is not userfriendly.
Make links with just the ID and let wordpress handle custom redirection to the page at that current point in time.
Are there better alternatives? I'm sure this is already solved somewhere, I just couldn't find it.
I got pushed in the right direction by a friend, I build it quite easily using option 2:
The getPermalink function is now much simpler:
function getPermalink($id) {
return get_option('home') . '/?f=' . $id;
}
I didn't make any custom redirection, I just checked at the homepage for a an 'f' being passed in the GET request:
$perma = $_GET['f'];
if(isset($perma) && !is_paged()) {
$customposts = get_posts('p=' . $perma );
foreach( $customposts as $post ) :
setup_postdata($post); ?>
//load the post
<?php endforeach;
}?>
If that is true the post will be fetched using the get_posts function by Wordpress. I also check the (normal) loop for the post that already has been served:
<?php while (have_posts()) : the_post();
if(get_the_ID() != $perma) { ?>
//load the post
<?php } endwhile; ?>

Categories