Using WordPress ‘background_image()’ PHP function

The background_image() WordPress PHP function is used to display the path of the background image.

Usage

Here’s a simple usage of the background_image() function:

echo background_image();

The function will output the URL of the background image.

Parameters

The background_image() function doesn’t require any parameters.

More Information

See WordPress Developer Resources: background_image()

Examples

Displaying the Background Image Path

In this example, we’re going to use the background_image() function to display the path of the background image. Here is the code:

// This will print the URL of the background image.
echo background_image();

Setting Background Image for a Div

Let’s use the background_image() function to set a background image for a div. Here’s how:

echo '<div style="background-image: url(' . background_image() . ')"></div>';

Adding Alt Text to an Image

You can also use the background_image() function to add an alt text to an image.

echo '<img src="' . background_image() . '" alt="Background Image">';

Setting Background Image for a CSS Class

If you want to use the background_image() function to set a background image for a CSS class, you can do it like this:

echo '.myClass { background-image: url(' . background_image() . ');}';

Displaying Background Image Path in a Paragraph

Finally, you can use the background_image() function to display the path of the background image in a paragraph.

echo '<p>The background image is at ' . background_image() . '</p>';

In each of the examples, the background_image() function is used to get the URL of the background image and use it in different contexts, such as setting the background image of a div or a CSS class, adding an alt text to an image, or simply displaying the path in a paragraph.