Ok. So I have this Wordpress site I'm working on and the client needs to have her post either link to an external link, a file url, or to the post itself. I have two custom fields setup, one is called "url", the other is called "file_url". I've gotten the "url" one to work but I'm not sure how I should add in the logic for the "file_url" custom post type, in case there is data for that one. I've been trying to get this to work for a while but I think my lack of knowledge is really hurting me. Yay for being a noob.
function.php brings in this file:
<?php
/**
*
* Permalink
*
* @package Theme
*/
add_filter( 'post_link', 'wpse_64285_external_permalink', 10, 2 );
/**
* Parse post link and replace it with meta value.
*
* @wp-hook post_link
* @param string $link
* @param object $post
* @return string
*/
function wpse_64285_external_permalink( $link, $post )
{
$meta = get_post_meta( $post->ID, 'url', TRUE);
$fileMeta = get_post_meta( $post->ID, 'file_url', TRUE);
$url = esc_url( filter_var( $meta, FILTER_VALIDATE_URL ));
return $url ? $url : $link;
}
Code from here with some edits: https://wordpress.stackexchange.com/a/72384/77860
EDIT
Got some support from a co-worker who is a genius. Here's the code in case someone needs it, this will pull the correct field depending on what's in the backend:
<?php
/**
*
* Permalink
*
* @package Theme
*/
add_filter( 'post_link', 'wpse_64285_external_permalink', 10, 2 );
/**
* Parse post link and replace it with meta value.
*
* @wp-hook post_link
* @param string $link
* @param object $post
* @return string
*/
function wpse_64285_external_permalink( $link, $post )
{
$url = $link;
if ($post->post_type == 'post'){
$meta = get_field( 'url', $post->ID);
$fileMeta = get_field( 'file_url', $post->ID);
if (isset($meta) && !empty($meta)){
$url = esc_url( filter_var( $meta, FILTER_VALIDATE_URL ));
}
if (isset($fileMeta) && !empty($fileMeta)){
$url = esc_url( filter_var( $fileMeta, FILTER_VALIDATE_URL ));
}
}
return $url;
}
The Code Works Prefect, Please check that your getting data on the custom fields. Seems your using ACF please check that the field names are correct.
External URL :
File URL :
I made the code to best practice and here are the below,
<?php
if (isset($meta) && !empty($meta)){
$url = esc_url( filter_var( $meta, FILTER_VALIDATE_URL ));
}else if (isset($fileMeta) && !empty($fileMeta)){
$url = esc_url( filter_var( $fileMeta, FILTER_VALIDATE_URL ));
}
?>