0

I am creating something which passes featured image URLs to a separate JavaScript file which uses parallax.js to create a parallax background for each entry for an archive page.

This works fine when each post has an image.

I have been working on having a default image where there is no featured image but am having problems on pointing to it. I want to keep the path relative so when I upload to the host there is no need to have an absolute path.

At the moment it goes something like this:

if ( has_featured_image() ) {
  $image_link_url = $featured_background_image;
} else {
  $image_link_url = get_template_url() . 'images/placeholder_bg.png';
}

This does not work. How would I get the result I am after? Ideally want to have the function result and string at the end as one single string in a variable.

1

Instead of

get_template_url()

user

get_template_directory_uri() for parent theme

and

get_stylesheet_directory_uri() for child theme or parent theme if not child theme present

NOTE: this will require a slash like so:

 $image_link_url = get_template_directory_uri() . '/images/placeholder_bg.png';
  • This solved the problem, thank you, was pulling my hair over something this simple – Galagargh Oct 14 '16 at 14:23
1

You can use has_post_thumbnail() instead of has_featured_image() and get_template_directory_uri() instead of get_template_url().

if(has_post_thumbnail()){
    $image_link_url = wp_get_attachment_image_url( $post_thumbnail_id, $size );
}else {
$image_link_url = get_template_directory_uri() . 'images/placeholder_bg.png';
}
  • this is actually exactly how my code looks now. was on my mobile and im bad with wordpress functions from memory – Galagargh Oct 14 '16 at 14:27
0

As far I've understood you want show a default image which you've store in a folder in your theme directory. So for that I think your code should be modeified a little bit-

if ( has_featured_image() ) {
    $image_link_url = $featured_background_image;
} else {
    $image_link_url = get_stylesheet_directory_uri() . '/images/placeholder_bg.png';
}

Please try the above code. I hope that will work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.