• Resolved rucativava

    (@rucativava)


    Hello,

    I want to write out some info entered in custom fields right below the image with caption=”capa” from each post single.php page.
    I think creating a filter is the right way to go, but I can’t seem to discover how to start coding this.
    I would create a filter that, upon rendering the_content(), if finds an image with caption=”capa” , would add a class to the image itself, and add some ‘<div …’ after this image.

    Any thoughts?

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

    (@bcworkz)

    You could hook the filter ‘the_content’. Your filter function will be passed the entire post string just before it is echoed out to the screen. With some clever string search and replace, you can achieve your goal.

    Thread Starter rucativava

    (@rucativava)

    Just to let you know that, not finding any other information, I followed your advice successfully.
    I used this https://codex.www.ads-software.com/Plugin_API/Filter_Reference/the_content and this
    https://php.net/manual/en/ref.strings.php .
    Maybe I might as well paste the code I wrote here, in case somebody stumbles upon this post and gets curious about my smudgy bites:

    function modify_capa($content) {
     	if(in_array('get_the_excerpt', $GLOBALS['wp_current_filter'])) return $content;
    	if (strpos($content,'alt="capa"')): ?>
    		<?php
    
    			// FIND CAPA
    			$capapos = stripos($content,'capa');
    			$imgend = strpos($content,'>',$capapos);
    			$imgend = $imgend;
    			$content_length = strlen($content);
    			$imgend_fromend = -1*($content_length - $imgend);
    			$imgstart = strrpos($content,'<',$imgend_fromend);
    			$img_length = $imgend - $imgstart+1;
    			$capa_img_tag = substr($content, $imgstart, $img_length);
    
    			//FIND ATTACHMENT ID
    			$id_start = strpos($capa_img_tag,'wp-image');
    			$id_end = strpos($capa_img_tag,' ',$id_start);
    			$id_string = substr($capa_img_tag, $id_start,$id_end-$id_start);
    			$capa_id = substr($id_string,strrpos($id_string, '-',-1)+1);
    
    			$capa = wp_get_attachment_image_src( $capa_id,'publication');
    			$new_capa = '<img class="capa-shadow" src="'.$capa[0].'" alt="capa" width="'.$capa[1].'" height="'.$capa[2].'" />';
    			echo $new_capa;
    		?>
    
    		<?php //INSERT NEW CODE ?>
    <div> HTML stuff <?php echo 'with php stuff'; ?> </div>
    
    		<?php 
    
    		//REMOVE OLD CAPA
    		$content = str_ireplace($capa_img_tag,'',$content);
    
    	endif;
    
    	return $content;
    
    }
    
    add_filter( 'the_content', 'modify_capa' );
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Attach code to image with named attributes’ is closed to new replies.