within my page.tpl.php I have the following code which makes some trouble in the backend. Therefore I want to solve it the better way, with preprocess functions.
if (!path_is_admin(current_path())) {
$pathArray = explode('/', current_path());
if (!empty($pathArray)) {
$path_to_node = url("node/".$pathArray[1]);
$img = '<img src="'.$theme_path.'/images/default.png" alt="Default" />';
if (!empty($path_to_node)) {
$menuChildArray = explode('/', $path_to_node);
if (!empty($menuChildArray[2])) {
$menuParent = $menuChildArray[2];
switch($menuParent) {
case "one":
$img = '<img src="'.$theme_path.'/images/one.png" alt="Pic tne!" />';
break;
case "two":
default:
$img = '<img src="'.$theme_path.'/images/two.png" alt="Pic two!" />';
break;
}
}
print $img;
}
}
}
But how can I realize this? To try it, I did the following:
I added a template.php to the Theme folder and added:
function set2015_preprocess_page(&$variables) {
$variables['set2015_pics'] = 'test';
}
Within page.tpl.php I then did:
<?php
print $set2015_pics;
But nothing is getting printed... What am I doing wrong here?
Thank you!
Presuming that set2015 is the name of your theme everything looks good so clearing cache with drush or at config/development/performance should make the variable show up. If set2015 is not the name of your theme then rename the function set2015_preprocess_page to YOURTHEME_preprocess_page
Debug it. Add some echo "I'm here"; above first if, then bellow it, then after second if and so on...to see what is executed and what's not. Try localizing the problem.
Related
I'm quite new to PHP, so this is probably a stupid question.
I have an if/else that I need to use in a return tag, but it doesn't work. How should I structure this?
This is the tag:
return '… <div class="read"><a class="read-more hvr-icon-forward" href="'. get_permalink($post->ID) . '">' . "CODE HERE" . '</a></div>';
This is what I need to output in "CODE HERE"
$status = of_get_option('read_more');
if (empty($status)) {
echo 'Sorry, the page does not exist.';
} else {
_e($status);
}
https://jsfiddle.net/33nv1xpa/1/
Do I get it right, you have a structure like
return *SOME_STRING* SOME CODE WITH ";" *SOME_STRING*
?
I would highly recommend, to create a string var containing the text you want to return and finally only return that string.
$echoCode = result from CODE HERE
$returnText = "<div>blalba</div>" . $echoCode . "<div>blabla</div>";
return $returnText;
You can do it by using the ternary operator, and putting the variable assignment in parenthenses.
return "...". (($status = get_option('status')) ? $status : _e()) ."...";
Otherways, I suggest to put this functionality in a function, or at least in a plain variable.
Coding like this makes the whole thing unreadable.
Also, you're trying to run a wordpess function in an online parser which will undeniably miss these features!
Well you can use the Php eval function (http://php.net/manual/en/function.eval.php). It evaluates a string as Php code. So you can assign the result of eval to a variable called $code_here:
$code_here = "$status = of_get_option('read_more');
if (empty($status)) {
echo 'Sorry, the page does not exist.';
} else {
_e($status);
}";
$code_here = eval($code_here);
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.
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.
How to write the following in PHP:
IF current page's name is pagex.php
THEN please load these additional CSS rules:
#DIVS { color:#FFF }
IF current page's name is anotherpage.php
THEN please load following CSS rules:
#DIVS { color: #000 }
like this:
<?php
if (basename(__FILE__) == 'pagex.php') {
echo '#DIVS { color:#FFF }';
} else if (basename(__FILE__) == 'anotherpage.php') {
echo '#DIVS { color:#000 }';
}
?>
PHP has some "magic constants" that you can inspect to get this information. Take a look at the ` __FILE__ constant.
The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, FILE always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.
So you can take this __FILE__ variable and execute the basename() function on it to get the file name. The basename() function returns the trailing name component of a path. Then you simply do a switch case to match the desired value -
$fileName = basename(__FILE__);
switch($fileName){
case 'pagex.php':
echo '<link .... src="some_stylesheet_file.css" />';
break;
case 'anotherpage.php':
echo '<link .... src="another_stylesheet_file.css" />';
break;
}
Your additional CSS rules can sit within those separate files.
Alternatively, if you don't want to split your css into multiple files, you can echo those specific rules into your page's head element like this -
echo '<style type="text/css">';
$fileName = basename(__FILE__);
switch($fileName){
case 'pagex.php':
echo '#DIVS { color:#FFF }';
break;
case 'anotherpage.php':
echo '#DIVS { color: #000 }';
break;
}
echo '</style>';
References -
basename()
php magic constants
You can just add in HTML head part one PHP if...else to load additional stylesheet according to page name.
<head>
<?php
if (basename(__FILE__) == 'one.php')
echo '<link .... src="style1.css" />';
elseif (basename(__FILE__) == 'two.php')
echo '<link ..... src="style2.css" />';
?>
</head>
you can use is_page() function of wordpress in a customize manner as it is working on regular php.code is:
<?php
$baseurl = 'http://www.example.com'; //set the base url of the site
$mypage1 = $baseurl."/pagex.php"; //add the rest of the url
$mypage2 = $baseurl."/anotherpage.php"; //add the rest of the url
$currentPage = $baseurl.$_SERVER['REQUEST_URI'];// this gets the current page url
if($currentPage==$mypage1) {
//do something with you style or whatever..
}
else if($currentPage==$mypage2)
{
//do something with you style or whatever..
}
?>
you have to change it according to your needs. i think it will help you.
happy coding!
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.