R
R
Ruslan Makarov2015-12-19 12:03:36
WordPress
Ruslan Makarov, 2015-12-19 12:03:36

How to use the "Relationship" field in Advanced Custom Fields?

Good morning!
I'm using the Advanced Custom Fields plugin, and I'm asking for a hint with the "Relationship" feature.
I'll tell you in order what I have:
- I added an arbitrary type of posts, now there are Posts (standard) and let's say "Cities"
- I added an extra in the plugin. the "Relationship" field
What I want to get as a result:
- When you select the necessary "Cities" in the record, they are displayed in the record as links, and in the record of an arbitrary type, links to the records in which they were selected are displayed.
I'll better show it with an example:
- Here I indicate "Cities" in the entry:
9edcb3685e9249328dbedba0789812ab.png
- And on the entry page they are shown like this:
72b24b8a2a93408786ac7058706c82cc.png
- This is done by code:

<?php
$posts = get_field('down-url');
if ($posts) { ?>
    <h3 class="related">Ссылки на "Города"</h3>
    <p>
    <?php foreach($posts as $post) { setup_postdata($post); ?>
        <a title="<?php the_title(); ?>" href="<?php the_permalink(); ?>"><?php the_title(); ?> »</a><br/>
    <?php } //End for each loop
    wp_reset_postdata(); //Restores WP post data ?>
    </p>
    <hr />
<?php } //End if ?>

- Tell me how to make "reverse" links displayed in the City Record.
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mr Crabbz, 2015-12-19
@Punkie

www.advancedcustomfields.com/resources/relationship
Section "Using WP_Query arguments":

<?php 

// get only first 3 results
$ids = get_field('down-url', false, false);

$query = new WP_Query(array(
  'post_type'      	=> 'conferences',   /// тут ваш тип записи
  'posts_per_page'	=> 1,     // тут указываем сколько постов вывести из relation.
  'post__in'		=> $ids,
  'post_status'		=> 'publish',     // тут лучше сменить на 'publish' - показать только опубликованные посты
  'orderby'        	=> 'rand',     // Тут указываем сортировку. Если убрать эту строку - отсортируются по дате.
));

?>

Thus, the $query will contain posts whose id's are listed in $ids. Well, then we output it anywhere in the post template with the usual loop:
<?php

if ( $query->have_posts() ) {
  while ( $query->have_posts() ) {
    $query->the_post(); ?>
        <a href="<?php the_permalink();?>"><?php the_title();?></a> 
<?php
  }
} else {
  // тут показываем что-то а-ля "Связанных постов нет" или просто ничего не делаем.
}

// Restore original Post Data
wp_reset_postdata();

?>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question