I’m currently diving into PHP and WordPress for a project involving WPBakery and a premium theme. To tailor it to my needs, I’ve ventured into creating a child theme and managed to locate and duplicate the template file I need to modify. It’s been quite a journey of exploration and learning thus far. However, I’ve hit a roadblock I can’t seem to navigate.
My objective is to fetch an Advanced Custom Fields (ACF) boolean value associated with each dynamically rendered image and, if true, apply a specific style. To achieve this, I require the post ID, which seems elusive through conventional methods I’ve researched online. The only workaround I’ve discovered is by extracting the post ID from the image URL using the $post_id = attachment_url_to_postid($image_url);
function.
While this method works perfectly when I manually input a URL copied from the GUID column in my database, it fails to function dynamically. This is because I need to manipulate the accessible URL beforehand. Firstly, I need to revert “https” back to “http”. Secondly, I must remove a size parameter resembling this pattern: http://example.net/wp-content/uploads/2019/08/schräg-87-010-b-720x200.jpg"
, where the -720x200
segment needs to be eliminated.
To tackle this, I’ve integrated the following function into my child theme’s functions.php file:
function convertUrl($url) {
// Step 1: Replace "https" with "http"
$url = str_replace("https://", "http://", $url);
echo "<script>console.log(1: " . $url . ");</script>";
// Step 2: Remove dimensions from the filename
$url = preg_replace('/-d+xd+(?=.w+$)/', '', $url);
echo "<script>console.log(2: " . $url . ");</script>";
return $url;
}
Despite implementing this function, it’s not yielding any results. I’ve also logged the URL before and after invoking the function in the template where it’s utilized, but it consistently outputs the same URL. I’ve been grappling with this for almost 1.5 days now and I’m at a loss. Any assistance would be greatly appreciated!
What I tried:
I attempted to implement a function in my child theme’s functions.php file to manipulate image URLs. Specifically, I aimed to replace “https” with “http” and remove dimension parameters from the filenames using str_replace()
and preg_replace()
functions respectively.
What I expected to happen:
I expected the function convertUrl()
to successfully transform the image URLs as intended. Upon invoking the function, I anticipated the URLs to be modified according to the specified replacements.
What actually resulted:
Despite implementing the function, it failed to produce the desired outcome. When logging the URLs before and after applying the function, they remained unchanged. Despite thorough troubleshooting over approximately 1.5 days, I couldn’t resolve the issue.
Shawn GB is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.