Answer the question
In order to leave comments, you need to log in
How to enter a list of links from a custom field in Wordprress?
I want to display similar posts, selecting them manually for each post. I found a suitable script that receives 'my_related_posts'
post IDs from an arbitrary field (they are indicated there separated by commas) and makes links to them.
if ($my_related_post_ids = get_post_meta($post->ID, 'my_related_posts', true)):
$related_args = array(
'posts_per_page' => -1, // сколько постов будет указано в админке, столько и выведется
'post__in' => explode(',', $my_related_post_ids), // в качестве значения нужно будет передать массив
'orderby' => 'post__in', // посты будут сортироваться в том же порядке, в котором они перечислены в админке
);
$my_query = new WP_Query($related_args);
// если посты, удовлетворяющие нашим условиям, найдены
if ($my_query->have_posts()):
// выводим заголовок блока похожих постов
echo '<h4 class="related">' . get_post_meta($post->ID, 'my_related_posts_title', true) . '</h4><ul class="relatedlist">';
// запускаем цикл
while ($my_query->have_posts()): $my_query->the_post();
echo '<li class="relatedlist-item"><a class="relatedlist-link" href="' . get_permalink($my_query->post->ID) . '"><div class="relatedlist-thumbnail">' . get_the_post_thumbnail(null, 'medium', array('alt' => get_the_title())) . '</div>' .
$my_query->post->post_title . '</a></li>';
endwhile;
echo '</ul>';
endif;
wp_reset_postdata();
endif;
$my_query->post->post_title
, and I want to prescribe my own. I could also write them, separated by commas, into another arbitrary field. How to change the code so that the link texts are also taken from another field and substituted in a loop?
Answer the question
In order to leave comments, you need to log in
To solve the problem, use the Advanced Custom Fields Pro plugin, it will allow you to add any number of post ID pairs + New title with a convenient interface to each post:
For example, the name of the relatives repeater field, the relative_id and relative_title subfields, then the code will look like this:
<?php if( have_rows('relatives') ): ?>
<ul>
<?php while ( have_rows('relatives') ) : the_row(); ?>
<li><a href="<?php $id = get_sub_field('relative_id'); echo get_the_permalink($id); ?>"><?php the_sub_field('relative_title'); ?></a></li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question