• I’m trying to figure out the (I’m sure simple) task of including a snippet into a page template.

    Here is the code I’m trying to add… maybe best as a shortcode? But still unsure how to accomplish it.

    <?php
    
    $post_object = get_field('location');
    
    if( $post_object ): 
    
    	// override $post
    	$post = $post_object;
    	setup_postdata( $post ); 
    	?>
    			  <div>
    				  
    				  <img src="<?php the_field('new_icon'); ?>" width="151" /></div>
    			  
        <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
    <?php endif; ?>

    Thanks for any help.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Hi milopop
    as I understand you, are you trying to edit a template file directly – or am I misunderstanding you?

    Code Snippets is a plugin that allows you to create custom php code as code blocks and to enable, disable, export and import as needed.

    do you have a theme template that you want to edit and are you working with a child theme?

    I wish you success

    Peter

    Plugin Author Shea Bunge

    (@bungeshea)

    Hi @milopop,

    My apologies for the delay in getting back to you.

    You can use a code snippet to filter page content, and if the current page uses a specific page template, append your custom content. Here’s an example:

    add_filter( 'the_content', function ( $content ) {
      
    	if ( 'page-full.php' !== get_page_template_slug() ) {
    		return $content;
    	}
    	
    	ob_start();
    	
    	$post_object = get_field('location');
    	
    	if ( $post_object ) {
    		// override $post
    		$post = $post_object;
    		setup_postdata( $post );
    		
    		?>
    		<div>
    			<img src="<?php the_field('new_icon'); ?>" width="151" />
    		</div>
    			
    		<?php
    		
    		wp_reset_postdata();
    	}
    
    	return $content . ob_get_clean();
    } );
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Inserting Snippets Into Code’ is closed to new replies.