Skip to content

Instantly share code, notes, and snippets.

@neilgee
Last active July 11, 2023 03:13
Show Gist options
  • Save neilgee/fec49841cfc8713c7380977a5c5928bd to your computer and use it in GitHub Desktop.
Save neilgee/fec49841cfc8713c7380977a5c5928bd to your computer and use it in GitHub Desktop.
Relationship Field ACF as Shortcode
<?php //<~ don't add me in
add_shortcode( 'tl_related_lights', 'tl_related_lights_relationship' ); // Add your shortcode here
// Add Relationship field between same CPT
function tl_related_lights_relationship() {
ob_start();
$posts = get_field('relationship_field_name'); // Add your ACF field in here
if( $posts ): ?>
<ul>
<?php foreach( $posts as $post): // variable must be called $post (IMPORTANT) ?>
<?php setup_postdata($post); ?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endforeach; ?>
</ul>
<?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
<?php endif; ?>
<?php
return ob_get_clean();
}
<?php //<~ don't add me in
add_shortcode( 'tl_related_lights', 'tl_related_lights_relationship' ); // Add your shortcode here
// Add Relationship ACF field between Projects and Lights
function tl_related_lights_relationship() {
ob_start();
$posts = get_field('tl_project_lights_link_used'); // Add your ACF field in here
if( $posts ): ?>
<ul>
<?php foreach( $posts as $p ): // variable must NOT be called $post (IMPORTANT) ?>
<li>
<a href="<?php echo get_permalink( $p->ID ); ?>"><?php echo get_the_title( $p->ID ); ?></a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<?php
return ob_get_clean();
}
@adamdexter
Copy link

Also- not sure this is worth a fork/commit- but here is a sample of using your snippet to pull ACF wysiwyg content:

//shortcode for WYSIWYG field type modified by adamdexter
// see https://www.advancedcustomfields.com/resources/wysiwyg-editor/
add_shortcode( 'footnotes', 'footnotes_wysiwyg' ); // Add your shortcode here
// Registers function "footnotes_wysiwyg" as shortcode "footnotes"
function footnotes_wysiwyg() {
	ob_start();
	
	$posts = get_field('footnotes'); // Add your ACF field in here

	if( $posts ): ?>
		<div>
		    	<?php echo get_field('footnotes'); ?>
		</div>
	<?php endif; ?>
	
	
	<?php
	return ob_get_clean();
	
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment