How to link Post Titles with custom URLs on single Posts in Genesis

Posted on
5/5 - (157 votes)

In Genesis Facebook group a user asked,

I am really not a coder and need some help resolving an issue. I am not even certain I am framing my question properly, but here goes.

I am in the process of redesigning and converting a site utilizing a non-Genesis custom child theme to a Genesis child theme. The current non-Genesis custom theme has a custom field containing a link (named “link”) defined in it.

I believe the following code in the loop section of single.php file applies the custom field “link” to the post title if the custom field is present.

<?php if (get_post_meta($post->ID, 'link', true)) { ?>
<h2><a href="<?php echo get_post_meta($post->ID, 'link', true); ?>" target="_blank"><?php the_title(); ?></a></h2>
<?php } else { ?>
<h2><?php the_title(); ?></h2>
<?php } ?>

I have successfully added the “link” custom field into the Genesis child theme, but I do not understand how to apply the “link” url to the post title when the custom field is populated. My question is, what code should be applied in what files to achieve the same link action when appropriate in the Genesis child theme so that the “link” field url is applied to the title if the post has a “link” field present?

Hope that made sense. Thanks in advance for any guidance you might have.

genesis_post_title_text filter can be used to wrap the single post titles with their corresponding custom links (if present).

Add the following in child theme’s functions.php:

// Filter Post Title Text to wrap the title in a custom URL (if present)
add_filter( 'genesis_post_title_text', 'sk_post_title_text' );
function sk_post_title_text( $title ) {
	if ( is_singular( 'post' ) ) {
		$single_post_link = esc_url( get_post_meta( get_the_ID(), 'single_post_link', true ) );

		if ( $single_post_link ) {
			$title = '<a href="'.$single_post_link.'">'.$title.'</a>';
		}

	}

	return $title;
}

where single_post_link is the name of the custom URL field. This can be created using ACF Pro.