Support

Account

Home Forums General Issues Pulling Custom Post Data into a Loop – using it throughout the loop Reply To: Pulling Custom Post Data into a Loop – using it throughout the loop

  • Circling back to this to provide a solution for someone who may be looking for it.

    I had three custom post types before:
    product
    container
    scent

    I changed the container and scent from custom post type to taxonomy.

    Again, the goal was to put content in a format that I could pull, based on the product custom field values (using ACF custom fields).

    Thus: Lavender Mason Candle $20

    Where “Lavender Mason Candle” is the product, “lavender” is the scent, and “mason candle” is the container. The $20 comes from a custom field on the container taxonomy.

    Solution (this is for a taxonomy.php page, but the main part at the bottom could very well work on others.)

       <ul>
    	<?php
    		// Get the current page taxonomy term info
    		$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); 	
    										
    		// args
    		$args = array(
    			'post_type'   => 'products', //
    			'tax_query'   => array(
    				array(
    					'taxonomy' => 'scents',
    					'field'    => 'slug',
    					'terms'    => $term,
    				),
    			)
    		);
    
    		// New Query
    		$custom_query = new WP_Query( $args );?>
    					
    		<?php if( $custom_query->have_posts() ) : while( $custom_query->have_posts() ) : $custom_query->the_post(); ?>
    				  	
    			<li>
    				<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('thumbnail'); ?></a>
    				<!-- For part of the title, I want to temporarily pull info from the $container -->
    				<a href="<?php the_permalink(); ?>" title="<?php the_title();?>: $<?php $container = get_field('container'); if( $container ): the_field('base_price', $container); ?>+<?php endif; ?>">
    				<!-- After the title, I want to revert back to the original post data-->					
    					<p><?php the_title();?></p>
    					<!--Now back again to the container-->	
    					<?php $container = get_field('container'); if( $container ): ?>
    					<p class="price">$<?php the_field('base_price', $container); ?>+</p>
    					<?php endif; ?>
    					<!--And back again to the original post data-->
    				</a>
    								
    			</li>
    		<?php endwhile; wp_reset_postdata();?>
    </ul>

    This is the main worker to help selectively pick what goes from where:

        <?php $container = get_field('container'); if( $container ): ?>
    					<p class="price">$<?php the_field('base_price', $container); ?>+</p>
    					<?php endif; ?>

    Hope this helps someone else and saves them three days of searching for answers for something similar.