Struggling to show image with ACF WordPress - php

I've been trying to display an image with ACF code and have just got it working, but I can't work out why some code works and some doesn't.
if(get_row_layout() == 'bq_product'):
$image = the_sub_field('affiliate_image');
$affiliate_url = the_sub_field('affiliate_url');
?><img src="<?php echo $image ?>"/><?php //This line doesn't work and just displays the raw URL on the front end
?><img src="<?php the_sub_field('affiliate_image') ?>"/><?php //This line works and shows the image
?>Link //Similarly, this line doesn't use the URL set in affiliate_url, but does if I pass "the_sub_field('affiliate_url')"
How do I use the variable names within the image src without it just showing the raw URL on the front end?
I've tried using "get_sub_field" variations but they don't seem to make a difference.

Exactly as #Stender commented, attempting to store variables using ACF the_sub_field() will not work.
Use get_sub_field() instead to store returned ACF field data to your variables.
Then access variable data based on what you have set the ACF fields to return with... array, ID or URL
See example below (based on affiliate_image ACF field return format URL)
// if row layout is 'bq_product'
if(get_row_layout() == 'bq_product'):
// sub field vars
$affiliate_image = get_sub_field('affiliate_image');
$affiliate_url = get_sub_field('affiliate_url');
// if $affiliate_image variable is not boolean false
if($image) {
echo '<img src="' . $affiliate_image . '" alt="" />';
}
// if $affiliate_url is not boolean false
if($affiliate_url) {
echo 'Link';
}
endif;
See example below (based on affiliate_image ACF field return format array)
// if row layout is 'bq_product'
if(get_row_layout() == 'bq_product'):
// sub field vars
$affiliate_image = get_sub_field('affiliate_image');
$affiliate_url = get_sub_field('affiliate_url');
// use this to dump $affiliate_image array to see data for image sizes etc
// echo '<pre>' . print_r($affiliate_image, true) . '</pre>';
// if $affiliate_image variable is array
if(is_array($affiliate_image) {
echo '<img src="' . $affiliate_image['url'] . '" alt="' . $affiliate_image['alt'] . '" />';
}
// if $affiliate_url is not boolean false
if($affiliate_url) {
echo 'Link';
}
endif;

Related

How to Display Remote Image?

I need to have a working remote IMG display using PHP, let's say like this:
<img src='$src' />
And I need to fetch the remote URL based on $id, where
<?php
$id = "brown_fox";
$url = "http://exampl.com/$id";
get_remote_img($url) {
// some code to get image which SRC is dynamic:
<img id="pic" src="sjf5d85v258d.jpg" />
$src="sjf5d85v258d.jpg";
return $src
}
?>
I hope I explained it understandably.
If I understand you correctly then you can do something like this:
<?php
...
get_remote_img($url) { ...
$src = get_remote_img($url);
// Concatenating the result to the elements src attribute:
echo '<img src='.$src.' />';
?>
What you're looking for is something like this:
<?php
$id = "brown_fox";
$url = "http://exampl.com/" . $id;
...
function get_remote_img($url) {
// some code to get image which SRC is dynamic:
$src="sjf5d85v258d.jpg";
echo "<img id=\"pic\" src=" . "\"" . $src . "\"" . "/>";
return $src;
}
?>
Also, if you want to send and receive query parameters in the URI dynamically through a form, you can take a look at GET Request in PHP.

How to Get Posts From Custom post type with WP Rest Api v1.2.5

I want to get the posts from post type = events but it is not showing the correct posts from events post type but from the actual WP-POST
<?php
// Get the JSON
$json = file_get_contents('http://coralgableschamber.org/wp-json/posts?filter[posts_per_page]=1&filter[post_type]=events');
// Convert the JSON to an array of posts
$posts = json_decode($json);
foreach ($posts as $p) {
echo '<p>Title: ' . $p->title . '</p>';
echo '<p>Date: ' . date('F jS', strtotime($p->date)) . '</p>';
// Output the featured image (if there is one)
echo $p->featured_image ? '<amp-img src="' . $p->featured_image->guid . '" width="150" height="110"></amp-img>' : '';
echo '<p>Content: ' . $p->content. '</p>';
}
The event post type have the following posts in it but it is not showing these
It is showing wrong post check this link: http://mxcounters.com/coralgables/AMP/front.html
What is wrong and how i can fix to make it work.
Thanks!
Try using http://coralgableschamber.org/wp-json/posts?type=events instead.
You can look at http://coralgableschamber.org/wp-json/ to see all available paths.

Fetch rss with php - Conditional for Enclosured image and not Enclosured

I'm working on a project and it's something new for me. I'll need to fetch rss content from websites, and display Descripion, Title and Images (Thumbnails). Right now i've noticed that some feeds show thumbnails as Enclosure tag and some others dont. right now i have the code for both, but i need to understand how i can create a conditional like:
If the rss returns enclosure image { Do something }
Else { get the common thumb }
Here follow the code that grab the images:
ENCLOSURE TAG IMAGE:
if ($enclosure = $block->get_enclosure())
{
echo "<img src=\"" . $enclosure->get_link() . "\">";
}
NOT ENCLOSURE:
if ($enclosure = $block->get_enclosure())
{
echo '<img src="'.$enclosure->get_thumbnail().'" title="'.$block->get_title().'" width="200" height="200">';
}
=================================================================================================
PS: If we look at both codes they're almost the same, the difference are get_thumbnail and get_link.
Is there a way i can create a conditional to use the correct code and always shows the thumbnail?
Thanks everyone in advance!
EDITED
Here is the full code i have right now:
include_once(ABSPATH . WPINC . '/feed.php');
if(function_exists('fetch_feed')) {
$feed = fetch_feed('http://feeds.bbci.co.uk/news/world/africa/rss.xml'); // this is the external website's RSS feed URL
if (!is_wp_error($feed)) : $feed->init();
$feed->set_output_encoding('UTF-8'); // this is the encoding parameter, and can be left unchanged in almost every case
$feed->handle_content_type(); // this double-checks the encoding type
$feed->set_cache_duration(21600); // 21,600 seconds is six hours
$feed->handle_content_type();
$limit = $feed->get_item_quantity(18); // fetches the 18 most recent RSS feed stories
$items = $feed->get_items(0, $limit); // this sets the limit and array for parsing the feed
endif;
}
$blocks = array_slice($items, 0, 3); // Items zero through six will be displayed here
foreach ($blocks as $block) {
//echo $block->get_date("m d Y");
echo '<div class="single">';
if ($enclosure = $block->get_enclosure())
{
echo '<img class="image_post" src="'.$enclosure->get_link().'" title="'.$block->get_title().'" width="150" height="100">';
}
echo '<div class="description">';
echo '<h3>'. $block->get_title() .'</h3>';
echo '<p>'.$block->get_description().'</p>';
echo '</div>';
echo '<div class="clear"></div>';
echo '</div>';
}
And here are the XML pieces with 2 different tags for images:
Using Thumbnails: view-source:http://feeds.bbci.co.uk/news/world/africa/rss.xml
Using Enclosure: http://feeds.news24.com/articles/news24/SouthAfrica/rss
Is there a way i can create a conditional to use the correct code and always shows the thumbnail?
Sure there is. You've not said in your question what blocks you so I have to assume the reason, but I can imagine multiple.
Is the reason a decisions with more than two alternations?
You handle the scenario of a feed item having no image or an image already:
if ($enclosure = $block->get_enclosure())
{
echo '<img class="image_post" src="'.$enclosure->get_link().'" title="'.$block->get_title().'" width="150" height="100">';
}
With your current scenario there is only one additional alternation which makes it three: if the enclosure is a thumbnail and not a link:
No image (no enclosure)
Image from link (enclosure with link)
Image from thumbnail (enclosure with thumbnail)
And you then don't know how to create a decision of that. This is what basically else-if is for:
if (!$enclosure = $block->get_enclosure())
{
echo "no enclosure: ", "-/-", "\n";
} elseif ($enclosure->get_link()) {
echo "enclosure link: ", $enclosure->get_link(), "\n";
} elseif ($enclosure->get_thumbnail()) {
echo "enclosure thumbnail: ", $enclosure->get_thumbnail(), "\n";
}
This is basically then doing the output based on that. However if you assign the image URL to a variable, you can decide on the output later on:
$image = NULL;
if (!$enclosure = $block->get_enclosure())
{
// nothing to do
} elseif ($enclosure->get_link()) {
$image = $enclosure->get_link();
} elseif ($enclosure->get_thumbnail()) {
$image = $enclosure->get_thumbnail();
}
if (isset($image)) {
// display image
}
And if you then move this more or less complex decision into a function of it's own, it will become even better to read:
$image = feed_item_get_image($block);
if (isset($image)) {
// display image
}
This works quite well until the decision becomes even more complex, but this would go out of scope for an answer on Stackoverflow.

If custom field has value, show in slidehow. Else hide

I'm using Wordpress and the PODS plugin and created the pod project. In project i've created a set of fields. One of those is project_slide. If this field has a value, I want to show this in a RoyalSlider on my frontpage.
I've started with this piece of code (= one slide).
<?php
$project = pods('project', array('limit' => -1));
while ($project->fetch()) {
echo '<div class="rsContent">';
echo '<img class="rsImg" src="' . $project->display('project_slide') . '" alt="' . $project->display('project_title') . '">';
echo '</div>';
}
?>
The problem is: each project I add, displays in the slider. Even if project_slide has no value. Any idea how to resolve this?
Just add an if-statement to the loop.
Hide Image example
In my example, I only add the slide when the value isn't [empty string]
while ($project->fetch()) {
if( $project->display('project_slide') !== ""){
echo '<div class="rsContent">';
echo '<img class="rsImg" src="' . $project->display('project_slide') . '" alt="' .$project->display('project_title') . '">';
echo '</div>';
}
}
Expand with a detection if the image actually exists
You could expand it with a file_exists to also check if it exists (for the items with value, but the image itself doesnt exists). Just make sure the file_exists is 2nd, that way it only checks if the file is present if the string is not empty (if-statements go from left to right)
$project->display('project_slide') !== "" && file_exists($_SERVER['DOCUMENT_ROOT'].$project->display('project_slide')`
Default image method:
Instead of showing it only when there is an image, you could always show it, but build a default-image logic:
$defaultImage = '/some/image.jpg'; // set a default image outside of the loop
while ($project->fetch()) {
$src= $project->display('project_slide') !== "" ? $project->display('project_slide') : $defaultImage; // set a default umage
echo '<div class="rsContent">';
echo '<img class="rsImg" src="' . $src . '" alt="' .$project->display('project_title') . '">';
echo '</div>';
}

Hide Div if no image in the loop

Im looking to create a condition in wordpress loop. if no image then image box (.thumbHome{display:none})
this is in my function.php
function getThumbImages($postId) {
$iPostID = get_the_ID();
$arrImages =& get_children('post_type=attachment&post_mime_type=image&post_parent=' . $iPostID );
if($arrImages) {
$arrKeys = array_keys($arrImages);
$iNum = $arrKeys[0];
$sThumbUrl = wp_get_attachment_thumb_url($iNum, $something);
$sImgString = '<img src="' . $sThumbUrl . '" alt="thumb Image" title="thumb Image" />';
echo $sImgString;}
else {
echo '<script language="javascript">noImage()</script>';
}
}
And my javascript:
window.onload = noImage();
function noImage(){
document.getElementByClassName('.thumbHome').css.display = 'none';
}
I tried:
window.onload = noImage();
function noImage(){
$('.thumbHome').addClass('hide');
}
RESULT: class hide added to all loop
I cant figure it another way, since im still new in coding.
thx
Well first of all, you don't want to call these functions on window.onload. That's going to immediately set all class instances of .thumbHome to hidden without any conditions.
Here's a very easy way to fix this issue. There are probably more intricate ways, but this works well.
In your main loop, add an unique id to each .thumbHome div based on the image id. So like:
echo '<div class="thumbHome" id="thumb-' . $iNum . '"> ... </div>';
// or you could you use the post ID, doesn't matter, as long as you are consistent
Then your else conditional (for whether there's a thumbnail) could be changed to:
else {
echo '<script type="text/javascript">noImage("#thumb-' . $iNum . '")</script>';
}
and your js function could be:
function noImage(var){
$(var).hide();
}
This is not necessary the best way to do this, it's just the best way with the situtation you find yourself in now.

Categories