WordPress Content / Image Manipulation

Aller Anfang ist nicht einfach und vor allem wen man mit WordPress ein wenig ausfallende Sachen möchte. Wie zum Beispiel ein oder mehrere Bilder in einem Beitrag mit einem extra DIV wrappen und dazu noch eine MetaInformation (get_post_meta) dazu zuschreiben.

Da mich diese Aufgabe ein paar Stunden gekostet hat, hier die Lösung für alle die so was suchen.

Aufgabenbeschreibung:

  1. Wrappe ein Bild mit einem extra DIV / SPAN
  2. Packe zu dem Bild ein eigenes Copyright Meta-Tag vom „Credit-Tracker-Plugin
  3. ohne das Template zu bearbeiten

Lösung:

Die Funktion „add_filter“ in der function.php

<!--?php // add class to image add_filter('the_content', 'addSpanOnImage', 12); add_filter('get_comment_text', 'addSpanOnImage'); add_filter('post_thumbnail_html', 'addSpanOnImage', 10, 3 ); function addSpanOnImage ($content,$postID="",$imageID="") { global $post; $newContent = $content; $copyMeta = empty($copyMeta) ? get_post_meta( $imageID, 'credit-tracker-author', true ) : ""; if(!empty($copyMeta)){ $copyright = '&lt;span class="copyright"&gt;'.$copyMeta.'&lt;/span&gt;'; $pattern = '/(&lt;img(&#91;^&gt;&#93;*)&gt;)/i'; $replacement = '&lt;span class="copyrightframe"&gt;'.$copyright.'$1&lt;/span&gt;'; $newContent = preg_replace( $pattern, $replacement, $newContent ); } else { $args = array( 'post_type' =&gt; 'attachment', 'numberposts' =&gt; -1, 'post_status' =&gt; null, 'post_parent' =&gt; $post-&gt;ID ); $attachments = get_posts( $args ); foreach($attachments as $attach){ $copyright = '&lt;span class="copyright"&gt;'.get_post_meta( $attach-&gt;ID, 'credit-tracker-author', true ).'&lt;/span&gt;'; $replacement = '&lt;span class="copyrightframe"&gt;'.$copyright.'$1&lt;/span&gt;'; $newContent = preg_replace('/(&lt;img.+?class="(.*)wp-image-'.$attach-&gt;ID.'(.*)".+?-->)/i', $replacement, $newContent);
        }
    }

    return $newContent;
}
?&gt;
Marc Finnern: Marc Finnern ist ein FullStack-Developer. Sein Fachgebiet ist TYPO3, WordPress und InterRed. Ob Plugin, Backend oder Frontend-Arbeiten anfallen, alles ist möglich und machbar, man braucht nur die passende Idee.

This website uses cookies.