I’m making a WordPress theme and I have a custom shortcode. The shortcode is wrapped around some content with an image in it. The shortcode use DOMDocument to extract the src of the image, and uses that url to make it a background-image on a new DIV.

Here’s the relevant code:

 //find image src
$html = do_shortcode($content);

$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($doc);
$src = $xpath->evaluate("string(//img/@src)"); # "/images/image.jpg"

echo '<script>console.log('.'"Source: '.$src.'");</script>';

$overlay_html = '';
foreach($xpath->evaluate("//*[contains(@class, 'sp-img-overlay')]") as $childNode) {
  $overlay_html .= $doc->saveHtml($childNode);
} 

//removes empty p tags from content
$content = do_shortcode($content);
$content = force_balance_tags($content);
$content = preg_replace('#<p>s*+(<brs*/*>)?s*</p>#i', '', $content);

//removes the actual images and captions
$just_text = $content;
$just_text = preg_replace('#(<figure.*?>).*?(</figure>)#', '', $just_text);
$just_text = preg_replace("/<img[^>]+>/i", "", $just_text);


//build output
//make src captured earlier the background image.
$output = '<div class="section-pairing full-bleed-mobile">'; 
    $output .= '<div class="section-pairing-img full-bleed-mobile '.$img_side.' '.$values['mobile_img_size'] .'" style=" background-image:url('. $src .')">';
        $output .= $overlay_html;
    $output .= '</div>';

    $output .= '<div class="section-pairing-text '.$text_side.'">';
        $output .= $just_text;
    $output .= "</div>";
$output .= "</div>";


return $output;

When I run this in my local dev environment, that console log . . .

echo '<script>console.log('.'"Source: '.$src.'");</script>';

. . . returns the correct path to the image and the shortcode works as intended.
But when I migrated to the server, everything else on the page works fine, but this shortcode doesn’t work and that console log returns “Source: ” with no url and there’s no image.

I’m new to Web development and really new to using DOMDocument so any suggestions on how to make this work would be appreciated.

Read more here: PHP DOMDocument operation returns expected value when run locally, but is empty when page runs on server


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: