Get post / page ID from ACF Link field

I'm trying to recieve post ID from link using ACF link field:

?php 
  $link = get_sub_field('offer_link');
  $id = get_the_ID();
    if( $link ): ?
    a href="#post-?php echo $id; ?" target="?php echo $link['target']; ?"?php echo $link['title']; ?/a
?php endif; ?

but instead of ID of link I get the ID of current page. How should it be done?

Topic id links Wordpress

Category Web


For anyone else trying this, if you need to get the post id from a subfield in a repeater you can use the get_sub_field with a false flag for the format:

if ( have_rows( 'repeater') ):
  while ( have_rows( 'repeater') ):the_row();
    $post_id=get_sub_field( 'item_name', false );
  endwhile;
endif;

The Page Link documentation actually shows how to retrieve the ID from a Page Link field. Just needed to do this myself and came across it. It worked well for me.

<?php 

// vars
$post_id = get_field('url', false, false);

// check 
if( $post_id ): ?>
<a href="<?php echo get_the_permalink($post_id); ?>"><?php echo get_the_title($post_id); ?></a>
<?php endif; ?>

The "false, false" parameters allow you to retrieve more details.


This works form me:

<?php 

$link = get_sub_field('offer_link');
$x = $link->ID;

if( $link ): ?>
<a href="#post-<?php echo $x ?>"><?php echo get_sub_field('offer_link_text'); ?></a>
<?php endif; ?>

and Post Object field.

Thaks for everyone for help :)


I don't think that you should use the Link field in your case, if you want to create relation with post object...

It would be much better to use Relation field, if you should be able to select many posts, or just Post Object, if it should be possible to select only one value.

If you go for the Post Object field type, then remember to set its Return Format to Post ID.

This way get_sub_field( 'your-field-name' ) will return exactly the ID of selected post.

If you want to display link to this post, you can always use echo get_permalink( get_sub_field( 'your-field-name' ) );

So this is your code after modifications (I've used your original name for the field, but it would be nice to change it too, I guess, since it doesn't contain link anymore):

<?php 
    $post_id = get_sub_field('offer_link');
    if ( $post_id ):
?>
<a href="#post-<?php echo esc_attr($post_id); ?>"><?php echo get_post_field( 'post_title', $post_id ); ?></a>
<?php endif; ?>

You can get a post's ID from a URL with url_to_postid(). Just pass it the URL to get the ID back:

$link = get_sub_field( 'offer_link' );
$id = url_to_postid( $link['url'] );

But if you want a field that will give you an ID of a selected page you should use probably use the Relationship field instead. It'd probably be much more efficient. It also means that if the URL to that post changes your saved data wouldn't cease to work like it would if you were saving the URL.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.