Support » Developing with WordPress » Using PHP inside Tailwind?

  • Can anyone help with best way to use a wp media image inside a tailwind class?

    <div class"bg-[url('<?php echo wp_get_attachment_image_src(19); ?>')]">

    This doesn’t work unless I expressively enter the url but I want the image to be entered dynamically.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz


    How would PHP code dynamically know what image URL to return? Obviously you could specify the ID directly, but that wouldn’t be very dynamic.

    Thread Starter rsheppard83


    Sorry maybe I didn’t explain very well. I’m doing it by id as I know what image I want to load but want it from the media library to get responsive image sizes rather than linking to specific image file statically.



    Since Tailwind’s arbitrary properties uses relative path, I suggest to create a custom function that trims domain name from attachment url.

    See below:

    function return_attachment_relative_path($attachment_id, $size) {
    	return explode(site_url(), wp_get_attachment_image_src($attachment_id, $size)[0])[1];

    Then you can echo the url:

    echo esc_url(return_attachment_relative_path(19, 'thumbnail'));

    I hope this helps.

    • This reply was modified 3 weeks, 6 days ago by MK. Reason: escaped url
Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.