Created
March 23, 2017 19:40
-
-
Save kellenmace/4f264bcbcf7cce8be47699d3a02b6985 to your computer and use it in GitHub Desktop.
Replacing the global $post object vs. not replacing it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Template part that DOES replace the global $post object: | |
?> | |
<div class="portfolio-items"> | |
<?php global $post; ?> | |
<?php foreach ( wds_eight_get_portfolio_posts() as $post ) : ?> | |
<?php setup_postdata( $post ); ?> | |
<div class="portfolio-image"> | |
<img src="<?php echo get_the_post_thumbnail_url( $post, 'post-thumbnail' ); ?>" alt="<?php echo esc_attr_e( 'Featured Image', 'wds' ); ?>"> | |
</div> | |
<div class="portfolio-details"> | |
<h2 class="title"><?php the_title( $post ); ?></h2> | |
<p class="description"><?php the_content(); ?></p> | |
<span class="client-name"><?php echo esc_html( get_post_meta( $post->ID, 'client_name', true ) ); ?></span> | |
</div> | |
<?php endforeach; ?> | |
<?php wp_reset_postdata(); ?> | |
</div> | |
<?php | |
// Template part that does NOT replace the global $post object: | |
?> | |
<div class="portfolio-items"> | |
<?php foreach ( wds_eight_get_portfolio_posts() as $post_id ) : ?> | |
<div class="portfolio-image"> | |
<img src="<?php echo get_the_post_thumbnail_url( $post_id, 'post-thumbnail' ); ?>" alt="<?php echo esc_attr_e( 'Featured Image', 'wds' ); ?>"> | |
</div> | |
<div class="portfolio-details"> | |
<h2 class="title"><?php echo esc_html( get_the_title( $post_id ) ); ?></h2> | |
<p class="description"><?php echo esc_html( wds_get_the_content( $post_id ) ); ?></p> | |
<span class="client-name"><?php echo esc_html( get_post_meta( $post_id, 'client_name', true ) ); ?></span> | |
</div> | |
<?php endforeach; ?> | |
</div> | |
<?php | |
// Helper function for the template part above: | |
/** | |
* Get a post's content. | |
* | |
* @param int|string $post_id The post ID. | |
* @return string $content The post's content or empty string on failure. | |
*/ | |
function wds_get_the_content( $post_id ) { | |
$content = get_post_field( 'post_content', $post_id ); | |
if ( is_wp_error( $content ) ) { | |
return ''; | |
} | |
return apply_filters( 'the_content', $content ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment