In wordpress there is a plugin that assigns a header graphic for each page. You call that header graphic by placing this code in your header.php file:
<?php if(function_exists('show_media_header')){ show_media_header();} ?>
This basically calls the image assigned and places it as an IMG in HTML.
I would like to have it called as a background image with CSS but don't know how. For example:
.header-graphic{ background:url("show_media_header();"); }
I know that will obviously not work but that should explain what I'm trying to do.
Any help would be great.
Thanks!
Depending on the scope of show_media_header() and that it actually returns the path to an image you could write the following:
.header-graphic{ background:url("<?php echo show_media_header(); ?>"); }
However this is of course under the assumption that your css is in the php-file, which wouldn't be recommended. You should look at using SASS or LESS instead.
It's generally a bad idea to serve static files (like CSS) dynamically, since it can't be cached effectively. So inserting the result of show_media_header() directly into your CSS is a no-go.
However, there is an alternative: Insert just that style into the HTML like so:
<h3 style='background-image: url("<?= show_media_header(); ?>");'>
Foo
</h3>
Which can then be further modified by CSS that is in a statically-served and unchanging file - for example:
h3 {
background-position: left 3px top 3px;
}
This of course assumes the function returns just the image URL; I've not used Wordpress personally.
Based on another comment, apparently this function generates a complete <img> tag (ugh!) so you might instead have to do something like this:
<h3>
<?= show_media_header(); ?>
Foo
</h3>
And style it as appropriate like so:
h3 img {
margin: 3px 0 0 3px;
}
I'm gonna post it down here because no one is considering your statement:
"and places it as an IMG in HTML"
You may have to edit you plugin output. Since show_media_header(); echo a value, the function itself is creating a <img> element. Look for the plugin file, search for the function and, either create another one, duplicating the original, something like show_media_header_bg where you manipulate the element, or change the original.
How about if you use descendant CSS selectors as such:
#page #header {
background-image: url("image.jpg");
}
#another-page #header {
background-image: url("another-image.jpg");
}
and so assign each page to its background image.
Here, I'm assuming you can grab into each page by an id (here called "page" and "another-page", and that your header template has an id of header. It would help to see some HTML to see how best to exactly achieve this via CSS.
Got it to work!
Dug around in the plugin PHP file and found this:
function get_media_header_url() {
global $post;
$post_id = $post->ID;
So I did this:
.header-graphic-background{ background:url("images/<?php echo get_media_header_url() ?>"); }
Works great!
You guys absolutely pointed me in the right direction. THANKS!!!
Related
Is it possible to get a background image in CSS like you normally do in HTML when working with WordPress. I've tried doing this but it doesn't work.
background-image: url("<?php bloginfo('template_directory'); ?>/images/parallax_image.jpg ");
PHP code cannot run in .css file, however you can use inline style, such as:
<div style="background-image: url("<?php //url ?>");">
or
<style>
.class-name {
background-image: url("<?php //url ?>");
}
</style>
The above would be useful when working with custom fields for dynamic image paths.
If the image is located in the theme directory, PHP won't be needed, let's say the image folder is directly under the theme folder /theme-name/images, and the stylesheet is /theme-name/style.css, then you can just add the background image to the css file as follows:
.class-name {
background-image: url("images/file.jpg")
}
You don't need to use PHP in this question, your CSS file is already in template folder, so you can call image just like this:
background-image: url("images/parallax_image.jpg");
So you don't need to know template path to call images from your theme.
If the image folder is in the theme folder you can use:
background-image: url("/wp-content/themes/themeNameHere/images/parallax_image.jpg ");
Just upload your image to the WordPress Media Library
After that, you can give the path of the uploaded file in your CSS like this:
background-image:url('/wp-content/uploads/2019/12/filename.png');
Note: Open the uploaded image, there will be a path
One way would be to add this CSS to a PHP page that has access to the bloginfo() function. Say in index.php, you would add...
<style>
.some-element {
background-image: url("<?php bloginfo('template_directory'); ?>/images/parallax_image.jpg ");
}
</style>
Another way is accessing image using css file location as the reference point, e.g.
.class-name{
background-image:url("../images/file-name");
//one level up, then images folder background-image:url("../../images-directory-02/images/file-name");
//two levels up, then two folders in
}
I was having this issue with adding a background image to my Underscores based theme and I found this works:
background: url('assets/img/tile.jpg') top left repeat;
I first tried:
background: url('/wp-content/themes/underscores/assets/img/tile.jpg');
but that didn't work for me.
Use a style attribute in the tag and use the css.
<div style="background-image: url("<?php bloginfo('template_directory'); ?>/images/parallax_image.jpg ");">
Your other html here
</div>
As many people have suggested already do not use php in .css ext as it won't get interpreted.
But if you really need to use php because of some reasons you only know as you not responding, you can change the extension of your stylesheet to .php
then you can have
customestyles.php
<?php
header("Content-type: text/css; charset: UTF-8");
$sectionImage = bloginfo('template_directory')."/images/parallax_image.jpg";
?>
<style type="text/css">
.selector{
background-image: url(<?php echo "$sectionImage";?>);
}
</style>
If your images folder is relative to your theme folder that is
theme-folder/images
and that of your css is in this structure theme-folder/css/your-css-file.css
you can easily just traverse the folder path in your css e.g
.custom-element{ background-image: url(../images/name-of-image.png) }
Short answer is you can not render PHP in a CSS file. I would suggest making sure your <rel> tag is setup correctly and just using the /images/parralax_iamge.jpg part.
Just find the corresponding element (tag, class or ID) with the browser tools/inspector in your page and add a CSS rule for that element, either in the stylesheet of the child theme or in the "customCSS" field of the theme options.
you can't add php code into .css files. but if you wanna do this using php see this.
As the others have suggested, you can simply set the background-image CSS property to do this.
However, none of the URLs that the other answers suggest worked for me.
I think the reason is because all of my images were stored in the "Media" area.
For all those who are storing your images in the "Media" area:
In order to find the URL to the image, you can:
Open the Admin dashboard of your site
Open the "Media" area
Click on the image you want to use
Copy the URL from the URL field, but only the portion after the domain name (e.g. domain-name.com)
Use this as your URL for the background-image property
I wouldn't recommend using the whole URL (using it without removing the domain name) because if your domain name ever changes, the URL will break.
Here's an example of what my full URL looked like: https://example.com/wp-content/uploads/2018/06/<Name of the Image>.jpeg, but I only used the /wp-content/uploads/2018/06/<Name of the Image>.jpeg portion.
In the end, my CSS property looked like this:
background-image: url("/wp-content/uploads/2018/06/<Name of the Image>.jpeg");
As a side note, the URL worked with both a beginning forward slash /wp-content/... and without one wp-content/....
In the first div you can see the result from the approved response, in the second div you can see the result from
<div style="background-image: url('<?= get_the_post_thumbnail_url(); ?>');">
The reason it does not work in the first div is because the parser thinks that the first block of text ends where the second " occurs.
You need to echo the get_the_post_thumbnail_url() function
For example
style="background-image: url('<?php echo get_the_post_thumbnail_url();?>
FOLDER STRUCTURE: THEME_FOLDER --> ASSETS --> IMAGES
For using inline CSS which i will not recomment as it create issues when doing optimization test using lighthouse however you can use
.title{backgroound:url(' /assets/images/title.png');
}
OR in theme CSS you can use
background: url('../images/tile.jpg');
Worked for me.
I want to get WordPress featured image in pseudo elements. I've used it in inline style using following code
<?php
$thumb_url = wp_get_attachment_image_src(get_post_thumbnail_id($whatWeDo_post->ID), 'single-post-thumbnail' );
?>
<div style="background-image: url(<?php echo $thumb_url[0]; ?>);">
But I want to use it in pseudo elements
Option 1
Your main concern here is caching. You don't want to write the background-image style into your external .css file because it will probably change on every page. But you don't want to clog up your main HTML file with lots of extra inline styles.
Your best bet is to split off just what you don't want cached (the background-image and the rest of the styles). We want to inline just what shouldn't be cached, and leave the rest as an external .css file.
Say the styles relevant to your Featured Images container are something like this:
figure::before {
display:block;
height:300px;
width:500px;
margin:0;
background-image:url();
background-size:cover;
background-position:center center;
}
Just leave your .css file exactly the same format (don't use .css.php), but pull out the background-image line.
Then in the header, place this:
<style>
figure::before {
<?php $thumb_url = wp_get_attachment_image_src(get_post_thumbnail_id($whatWeDo_post->ID), 'single-post-thumbnail' );
background-image: url(<?php echo $thumb_url[0];?>);
}
</style>
Bonus - Another Option Just for Fun
The second option is to use a .php file with a .css HTTP header. I like to name my files something like:
styles.css.php
Advantages
This lets you use WordPress variables and data, as well as the entire power of PHP, directly in your stylesheet. But it's still sent to the browser as a .css file, so you can enqueue it like normal. It's the easiest to implement. Note, be sure to include the global post object.
Disadvantages
Do you use resource caching? If you .css files are cached, you're going to run into a problem because the file won't change on each page. In your specific case, the Featured Image will be different on each page. If you don't cache, it should be fine, but you absolutely should be caching, so you should probably skip this option.
Tweak on Bonus Option
If you like Option 1 but you do cache (which you should), you can take a middle ground. Create your file the same as above, something like:
styles.css.php
Instead of enqueueing it the official way using wp_enqueue_style, you can read the file with PHP's include function.
Create a function in your functions.php file:
function writeInlineCSS() {
include TEMPLATEPATH . '/styles/styles.css.php';
}
Then in your header, add:
<style>
<?php writeInlineCSS(); ?>
</style>
The CSS will be pulled in and written inline.
Advantages
Caching won't be a problem. Also you won't have a large render blocking .css resource. Plus the advantages from Option 1.
Disadvantages
You are including potentially a massive chunk of CSS inline. Possibly too much.
This is pulling from Mr Lister's comment, but here's a method of doing this. It's not the best way to structure the html, but it should work:
<?php $thumb_url = wp_get_attachment_image_src(get_post_thumbnail_id($whatWeDo_post->ID), 'single-post-thumbnail' ); ?>
<div class="myDiv"></div>
<style type="text/css">
.myDiv:before{
background-image: url('<?php echo $thumb_url[0]; ?>');
content: '';
}
</style>
I'm not sure if you'll run into some browser compatibility issues with older browsers and the tag outside of the , but it should work in modern browsers.
In my gallery I want to show my images, but I have two formats of images: 1/1:square format, 2/3:portrait format.
I created a class (result) for my ul container and I add the images to it. By modifying some properties I center it vertically and horizontally. Some images appear smaller because of their format I can't just let width (8em).
My question is: Can I add frm as an attribute to my image tag like src? If yes , I'll have this value from my database.
My script doesn't work. My Javascript is:
$(document).ready(function() {
if ($("ul.result li img").attr('frm')='1/1')
{
$("ul.result li img").css('width','10em');
}
if ($("ul.result li img").attr('frm')='2/3')
{
$("ul.result li img").css('width','8em');
}
});
Since you are using jQuery you can use the data method (http://api.jquery.com/data/) and properties on the elements in your html to store whatever it is you want. For your reference, that looks like:
HTML
<img src="file" data-format="square" />
Javascript
$(function () {
$("img").each(function () {
if ($(this).data("format") == "square") {
// process square image element ("this")
} else {
// process normal image
}
});
});
Now, that said - as others have noted you might consider using css classes to change your style rather than writing a bunch of Javascript code. The only reason I would consider writing the javascript (as opposed to css) is if there are complicated calculations that need to happen. Most of the time, though, if you structure your html correctly you can do whatever you need with pure css (no Javascript).
Why are you even using javascript for this?
You have a database property, and you're changing a css property based on a database property. That's what classes are for!
<img class=<?php (img.frm=="1/1"?"square":"portrait") ?> src=..... />
Then, in your css:
.square{
width: 10em;
}
.portrait{
width: 8em;
}
If you want to add a home made attribute, use a HTML5 data attribute,
so it is valid : data-portrait and data-landscape will do fine.
those attributes can be access via CSS or js
To answer your question:
YES you can, but i advise to use :data-frm as attribute name and avoid the use of special caracter in values.
Some reading from W3C :)
I have a small problem with my PHP code and It would be very nice if someone could help me. I want to display an image when hovering over a link. This is the link with the PHP code that I have now:
<?php if ( has_post_thumbnail() ) {the_post_thumbnail();} else if ( has_post_video() ) {the_post_video_image();}?>
This code shows a image, but I want to execute this code when hovering over the link with the image:
<?php echo print_image_function(); ?>
The code also shows a image that belongs to a category. I don't want the initial image to disappear I simply want to show the second image on top off the first image when hovering over the first image.
I don't know if it is helpful but I use Wordpress and I am not a PHP expert. I even don't know if this is going to work. Thats why I am asking if somebody can help me with this.
Thanks in advance
THANKS EVERYONE
I want to thank everybody that took the time to read my post and helped me by giving their solution.
I didnt exspect so many answers in such a fast time. After spending a few hours trying it to get it to work with PHP, CSS and Javacript, I stumbled upon the following question on this website: Solution
It was exactly where I was looking for and with a few modifications to fit my needs, I got it to work. Sometimes things can be so easy while you are looking for the hard way. So for everyone that has the same problem: You can use one of the solutions that where given by the awesome people here or take a look at the link above.
Thanks again! :)
You can do this with CSS (if you so please and this fits with your overall architecture) - here is an example using the :hover condition and :after pseudo element.
html
<img src="http://www.gravatar.com/avatar/e5b801f3e9b405c4feb5a4461aff73c2?s=32&d=identicon&r=PG" />
css
.foo {
position: relative;
}
.foo:hover:after {
content: ' ';
background-image: url(http://www.gravatar.com/avatar/ca536e1d909e8d58cba0fdb55be0c6c5?s=32&d=identicon&r=PG);
position: absolute;
top: 10px;
left: 10px;
height: 32px;
width: 32px;
}
http://jsfiddle.net/rlemon/3kWhf/ demo here
Edit:
Always when using new or experimental CSS features reference a compatibility chart http://caniuse.com/ to ensure you are still in your supported browsers. For example, :after is only supported starting IE8.
You cannot randomly execute server side code on the client side.
Try using javascript AJAX requests instead.
PHP is a server-side language; you can't get PHP to execute after the page has loaded (because PHP completely finishes parsing before the page loads). If you want hover events, you need JS.
Firstly you don't need the elseif statement. An else will serve the same purpose, unless you intend to have blank tags where neither a thumbnail or a video image are present.
<a href="<?php the_permalink(); ?>">
<?php
if ( has_post_thumbnail() )
{
the_post_thumbnail();
}
else
{
the_post_video_image();
}
?>
</a>
You can't explicitly use PHP for client side functionality. You will need to use javascript or jquery to supply the on hover capability.
Jquery example:
$(function() {
$('a').hover(function() {
// Code to execute whenever the <a> is hovered over
// Example: Whenever THIS <a> tag is hovered over, display
// the hidden image that has a class of .rollover
$(this + ' .rollover').fadeIn(300);
}, function() {
// Execute this code when the mouse exits the hover area
// Example (inline with above example)
$(this + ' .rollover').fadeOut(300);
});
});
To have an image placed on top of another image you would need to make sure your CSS uses absolute positioning for the images with the image that is to overlay the other on hover is given a z-index value higher than the image to sit underneath it.
Hope this helps.
You'll need some JavaScript and/or CSS to make this work, since PHP is on the server side, not in the client browser.
On my Drupal site, I have made a Users page using the Views module, which is simply a nicely styled grid (HTML table) of users. I'm displaying a few fields for each one, and both the name and the profile picture have been set to link to the user node.
What is the best way to change it so that the whole cell (HTML td) links to the user node? EDIT: I'm not concerned with adding the HTML link tags, but with accessing each profile page's URL.
I've looked into modifying the theme of the view (over-riding the Style output e.g. views-view-grid--users.tpl.php), but cant see an elegant way to get the URL of the user node.
EDIT: I've implemented a temporary solution in javascript which looks into the HTML of each cell, extracts the first link's URL, and uses that, but is there not a better way of doing this using the Drupal variables somehow?
Thanks for your help.
How about something like this...no JavaScript needed
In your table:
<td>the link</td>
...
In your CSS file:
.td_link {
display: block;
width: 100%;
}
So basically all you need to do is add a class to your link, and a small snippet of CSS.
OK I found a better (super simple) way of extracting the profile URL, and also I over-came a few issues with the whole block-link solution (attributed to espais), which I thought were worth documenting. So here is the complete solution to my original problem:
1) Add a custom template file to override views-view-fields.tpl.php (see http://views-help.doc.logrus.com/help/views/using-theme - thanks to barraponto for the useful link). In this custom file, you should wrap all the code in a link, and add a clear-fix div just before the end to stretch the link to the full height of the container.
<a class="td-link" href="user/<?php print $row->uid; ?>">
...
<div class="clear-fix"></div>
</a>
2) Now you need to get rid of any other links from inside each grid element, as you are not allowed to nest HTML links (produces really weird behaviour). First thing to do is edit the View, and make sure none of the fields have "link this field to it's user" checked. Then if you want to include the profile picture field, you need to add a small fix module because by default there's no way to stop this field being a link! You can get the module from this comment: http://drupal.org/node/720772#comment-2757536
3) Finally the CSS. Add the following to your theme's style.css:
a.td-link {
display: block;
color: #000;
text-decoration: none;
border: 1px solid #E9EFF3;
}
a.td-link:HOVER {border-color: #85b3d4;}
a.td-link label {cursor: pointer;}
div.clear-fix {clear: both;}
This removes the link formatting from the text (as we want the whole block to look like a link, not just the text), and stretches the link out to fill the container. It also makes the cursor graphic consistent, and adds a nice border effect when you mouse-over the block. Remember you can also add a custom CSS class to your View, which makes it much easier/neater to select elements for styling in your CSS code.
It's important to distinguish between actual links, with <a> tags, and arbitrary elements you can click. Even if you don't care about semantics, you should care about your visitors not running JavaScript, especially search engines.
Rather than turning a block element into a link, you should turn a link into a block element, as espais suggested. One way to get more control over the markup is using custom fields to add opening and closing tags for your link around the rest of your fields.
spais and scott-reynen are right. but instead of placing every field under multiple <a> elements, each styled with css to turn them into blocks (which can have margin and padding), why not use a single <a> element?
if everything is meant to link to the same place, you can place it all together under a single <a> element, although every element should be an inline element (<span> instead of <div>). you can do it by changing the row template: check http://views-help.doc.logrus.com/help/views/using-theme
in your case, copy templates from inside the views module to your theme folder, and rename it accordingly as your view "Theme: Information" says. make sure there is no <div> or <p> or any other block element being output. if you need to break lines, use <br>.