Support

Account

Home Forums Front-end Issues Link Field Array within Function

Helping

Link Field Array within Function

  • Hi,

    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 and an Array it won’t pass through the target=”_blank” when clicked.

    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 );
    }

    Any help would be greatly appreciated.

    Thanks

  • The filter you are using can only be used to filter the actual URL and does not have the ability to alter any of the properties of the <a> element. What function are you calling to get the entire link element?

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.