Site icon Hip-Hop Website Design and Development

Override a Post’s URL with Advanced Custom Fields Function

I have a field on specific post pages which allows the user to create a new link to forward the user to a completely new URL (this is so it still appears within the filtering of Post Content and has a name, excerpt and thumbnail – but directs the user offsite)

So I found a function which allows that, but although it’s a Link field and an Array it won’t pass through the target=”_blank” which is clicked when you add the link on the post page.

I feel it’s because I need to update the function to look for if the “Open in New Window” is ticked.

This is inside functions.php

function prefix_custom_link_option( $url, $post ) {
    // Create an array of post types to skip.
    $skip_post_types   = array(
        'attachment',
    );

    // page_link gives the ID rather than the $post object.
    if ( 'integer' === gettype( $post ) ) {
        $post_id = $post;
    } else {
        $post_id = $post->ID;
    }

    // Check if the current post type should be skipped.
    if ( in_array( get_post_type( $post_id ), $skip_post_types, true ) ) {
        return $url;
    }

    // Get the custom_link if one exists.
    $custom_link = get_field( 'new_page_link', $post_id );

    if ( $custom_link ) {
        $url = $custom_link['url'];
        $url_target = $custom_link['target'] ? $custom_link['target'] : '_blank';      
    }

    return $url;
}

/**
 * Add filters for post_link, page_link, and post_type_link to update Custom Link
 */
foreach ( [ 'post', 'page', 'post_type' ] as $post_type ) {
  add_filter( $post_type . '_link', 'prefix_custom_link_option', 10, 2 );
}

I know I need to update the return $url; to check for the target checkbox, but not sure how.

Any help would be greatly appreciated.

Thanks