everyone!
There is a problem at Wordpress with CPT and ACF.
I have ACF fields ('previouspost' and 'nextpost) at my CPT "portfolio" posts. I need every post to get previous and next post links to ACF fields. Code, which I use don't make anything, fields are empty, no errors and warnings
function update_portolio_metadata(){
$args = array(
'post_type' => 'portfolio', // Only get the posts
'post_status' => 'publish', // Only the posts that are published
'posts_per_page' => -1 // Get every post
);
$posts = get_posts($args);
foreach ( $posts as $post ) {
$previouslink = previous_post_link();
$nextlink = next_post_link();
update_post_meta( $post->ID, 'previouspost', $previouslink);
update_post_meta( $post->ID, 'nextpost', $nextlink);
}
}
add_action('init','update_portolio_metadata');
Updated, checked and work
function update_portolio_metadata(){
$args = array(
'post_type' => 'portfolio', // Only get the posts
'post_status' => 'publish', // Only the posts that are published
'posts_per_page' => -1 // Get every post
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$previouslink = get_permalink(get_adjacent_post(false,'',false));
$nextlink = get_permalink(get_adjacent_post(false,'',true));
update_post_meta( get_the_ID(), 'previouspost', $previouslink);
update_post_meta( get_the_ID(), 'nextpost', $nextlink);
endwhile;
}
add_action('init','update_portolio_metadata');
There functions works in the loop only. You can use wp_query instead of get_posts.
Your code should be like this:
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$previouslink = get_previous_post_link();
$nextlink = get_next_post_link();
update_post_meta( get_the_ID(), 'previouspost', $previouslink);
update_post_meta( get_the_ID(), 'nextpost', $nextlink);
endwhile;
}