Hide Div if no image in the loop - php

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.

Related

Images are displaying vertically rather horizontally

Update: After looking at my HTML code in browser I figure out I need to only run the SQL code inside php just once in foreach loop and the images will be displayed horizontally. I was wondering how do I make that sql code run only once in that loop?
When I write the below code inside foreach ($ffs as $ff) {
Code:
echo "<h4 class='text-right'>{$Data[$increaseForText]["username_for_info"]}</h4>";
echo "<h2>{$Data[$increaseForText]["_name"]}</h2>";
echo "<p>{$Data[$increaseForText]["_desc"]}<p>";
So when this code is inside that foreach loop the images displays in vertical and I want my images to be displayed in horizontal (one next to other). But, if I remove that code from foreach and put it outside foreach code the image are displayed horizontally and works fine. I have tried CSS to display the image horizontally, but it only works if I remove that code from foreach. For some reason the above code (In foreach) somehow forcing the images to display in vertical, so no matter what I do it displays in vertical (the images).
I can't put my code outside foreach. I know I can use foreach to loop through my SQL code and it works fine, but the thing is I want it to work like first load images then first row only from sql, then 2nd image and 2nd row from sql and for that to make it work the only way is to put inside foreach my sql code, so it loads one at a time or else if I put it outside foreach It will load all the data of sql at once (1 row to 9 let's say) then all the images which makes no sense. I am storing my images in my hosting website files.
My question is how do I force my images to display horizontally one next to other?
My code:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');
require "navigationbar.php";
require "testing.php";
?>
<html>
<head>
<link rel="stylesheet" href="userprofilestyl.css">
</head>
<body>
<hr>
<?php
global $username;
//username to get data of specific user
$username = $_SESSION['name'];
//to get image by username
$image = "images/$username";
global $increaseForText;
$increaseForText = 0;
function listFolderFiles($dir, $username, $increaseForText)
{
//getting images
$ffs = scandir($dir);
unset($ffs[array_search('.', $ffs, true)]);
unset($ffs[array_search('..', $ffs, true)]);
// prevent empty ordered elements
if (count($ffs) < 1) {
return;
}
$column_count = 0;
$sql = "select username_for_info, _name, _desc
from info_desc where username_for_info = '$username'";
try {
require "testing.php";
$stmt = $conn->prepare($sql);
$stmt->execute();
$Data = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<div class="image-container">';
foreach ($ffs as $ff) {
//select data from database
$s = "'<li>'.$ff";
$saving = "$dir/$ff";
$string = "$saving";
global $string_arr;
$string_arr = (explode("/", $string));
$sav;
$sav = '<li>' . $ff;
global $sa;
$sa = "$ff";
if (is_dir($dir . '/' . $ff)) {
listFolderFiles($dir . '/' . $ff, $username, $increaseForText);
}
//printing image
if (is_file($saving)) {
echo '<img src="' . $saving . ' " width="100" height="100" alt="Random image" />';
}
//printing text
echo "<h4 class='text-right'>{$Data[$increaseForText]["username_for_info"]}</h4>";
echo "<h2>{$Data[$increaseForText]["_name"]}</h2>";
echo "<p>{$Data[$increaseForText]["_desc"]}<p>";
$increaseForText++;
}
} catch (PDOException $e) {
echo '{error":{"text":' . $e->getMessage() . '}}';
}
echo '</div>';
}
listFolderFiles($image, $username, $increaseForText);
?>
</body>
</html>
Add this to your css file:
.image-container{
display:inline-flex;
flex-flow:row;
}
This will change the flow of every element inside the div with the class "image-container" from vertically to horizontally
Foreach has nothing to do with making the images display vertically, there should be something wrong with the HTML or CSS. Make sure your tags are closed, such as your p and li tags.
There are alot of ways to make the images display horizontally, it would easier if you can send a jsfiddle or a code snippet.
But try this on .image-container:
display: flex !important;
flex-flow: row;

How correctly refresh included PHP file?

I'm just a persistent beginner and I've met another obstacle in my way, so I hope that you'll help me one more time... :) I've got that HTML:
<div class='hold'><?php include 'image.php'; ?></div>
<div class='refresh'>Get new image</div>
And that PHP code:
<?php
$dir = 'images/';
$img = array();
if(is_dir($dir)) {
if($od = opendir($dir)) {
while(($file = readdir($od)) !== false) {
if(strtolower(strstr($file, '.'))==='.jpg') {
array_push($img, $file);
}
}
closedir($od);
}
}
$id = uniqid();
$smth = array_rand($img, 1);
echo '<img src=' . $dir.$img[$smth] . '?' . $id . ' width="200px" height="50px" />';
echo '<input type="hidden" value=' . $id . ' />';
?>
So now when I'm looking at my page I see in the <div class='hold'></div> my img from the folder images, and it's allright. BUT when I click on the <div class='refresh'></div> I obviously want to get another img from my folder, but I dunno how to accomplish that trick correctly.
I know that first answer will be USE AJAX, and I know that I can do something like
function loadGraphic() {
$('.hold').load('image.php');
};
loadGraphic();
and then $('.refresh').click(loadGraphic); but when I'm trying to do that in response from server I get TWO THINGS: image.php and, of course, something like car.jpg?573c4e010c7f6... But I very-very wanna get just ONE looking like
car.jpg?573c4e010c7f6
or
image.php?573c4e010c7f6 - I don't care...
So... I hope you've got my concept... maybe I'm asking for miracle - I dunno! Any, absolutely any help will be appreciated :)
Try it the following way:
JS function:
function loadGraphic() {
$.get("image.php", function(data) {
$(".hold").html(data);
});
};
Html:
<div class='refresh' onclick='loadGraphic()'>Get new image</div>

PHP not getting right link from path

Ok, so I have literally never been so confused. As you can see I have pretty much the same function twice here (I know that may seem stupid but it is just easier for me to read for my page when it's like this - but that isn't the point of this)
The first one goes to the link it's given (http://www.blade-edge.com/images/KSA/Flights/craft.asp?db=dunai) then follows the path to get the img src of http://i.imgur.com/8t5rwWh.png
But the second function doesn't get the src of the image it's pointing to (which would be http://i.imgur.com/jWWUEqt.png) but instead gets the src for a completely different image on the page http://www.blade-edge.com/images/KSA/Flights/prev.png.
I am sure this is a really stupid mistake that I have just overlooked but I can't work it out.
Anyone?
function getImage(){
$page = file_get_html(getPageURL());
$element = $page->find("html/body/div/div[1]/center/table/tbody/tr[1]/td/table/tbody/tr/td[1]/div/div/img");
$imgLink = $element[0]->getAttribute("src");
echo "<img id='shipImage' src='".$imgLink."'></img>";
}
function getMap(){
$page = file_get_html(getPageURL());
$element = $page->find("/html/body/div/div[1]/center/table/tbody/tr[2]/td/center/img");
$imgLink = $element[0]->getAttribute("src");
echo "<img id='shipMap' src='".$imgLink."'></img>";
}
The following works for me:
function getImage($imageType){
$page = file_get_html(getPageURL());
$element = $page->find("/html/body/div/div[1]/center/table/tbody", 0)->children($imageType)->find("img");
$imgLink = $element[0]->getAttribute("src");
return $imgLink;
}
echo "<img id='shipImage' src='" . getImage(0) . "'></img>"; // Spacecraft image
echo "<img id='shipMap' src='" . getImage(1) . "'></img>"; // Map image
I won't try to guess the reason behind the problem, as I do not know the innards of the library.

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.

PHP - Inject script into the <head>

Run into a bit of a sticky situation which I can't seem to wrap my finger around. Basically what I am trying to achieve is having the ability to inject different Javascript files on different page.
Some simple, random example:
Page 1: import jquery.js
Page 2: import mootools.js
So what I have done is, I've created a function called addScript() like so:
function addScript($file) {
$script = '';
$script .= '<script src="'. REL_PATH . '/path/to/file/' . $file . '">';
$script .= '</script>';
return $script;
}
so if I call addScript('jquery.min'); it, outputs correctly.
What I now want to do is replace the closing </head> tag with the output from the above function. If I do the following then it works fine:
ob_start();
require_once("models/header.php");
$contents = ob_get_contents();
ob_end_clean();
echo str_replace('</head>', addScript('jquery.js') . '</head>', $contents);
However I would like this to be a little more dynamic as there may be multiple script that I need to inject on each page like so:
addScript('script.js');
addScript('script2.js');
addScript('script3.js');
I then thought of creating a getHead() function with a foreach loop inside and returning str_replace there instead but this did not work.
Can anyone guide my in the direction to dynamically inject as many script as required and output the last bit of the head?
Why not do something like this:
class Assets {
private static $css = array();
private static $js = array();
static function add_style($path) {
self::$css[] = $path;
}
static function add_script($path) {
self::$js[] = $path;
}
static function get_styles() {
$output = '';
foreach(self::$css as $path) {
$ouput .= '<link rel="stylesheet" href="'. $path .'" />' . "\n";
}
return $ouput;
}
static function get_scripts() {
$output = '';
foreach(self::$js as $path) {
$ouput .= '<script type="text/javascript" src="'. $path .'"></script>' . "\n";
}
return $ouput;
}
}
Then anywhere in your project:
Assets::add_style('path/to/style.css');
Assets::add_script('path/to/jquery.js');
And in header.php:
<head>
<!-- other header stuff -->
<?php echo Assets::get_styles(); ?>
<?php echo Assets::get_scripts(); ?>
</head>
Is much more convenient, and you can can extend the class to do more fancy stuff.
Disclaimer: there is much debate about using static vars, as they look like globals. I agree, but this is quick-and-dirty and works no matter what kind of framework you use. You can also make the variables oldschool instance vars, but then you'll have to pass the assets object to the header.php as well.
What's wrong with the following??
echo str_replace('</head>',
addScript('jquery.js').
addScript('jquer1.js').
addScript('jquer2.js').
addScript('jquer3.js').
'</head>', $contents);
How about you put the ob_start(); in header.php. Then your function is:
function addScript($file) {
$script = '<script src="'. REL_PATH . '/path/to/file/' . $file . '"></script>';
echo str_replace('</head>', addScript('jquery.js') . '</head>', ob_get_clean());
}
Then:
addScript('script.js');
This method keeps the output buffer going and you can manipulate it later in the script whenever you want. just as you do with the addScript().

Categories