0

I want the conditional to be applied and that it is only displayed on pages, but it does not work, what is wrong?

    function luc_add_cutom_fields_to_content( $content ) {

    $custom_fields = get_post_custom();

    $content .= "<div class='cta-div'>";

    if( isset( $custom_fields['luc_name'] ) ) {
         $content .= '<h3> '. $custom_fields['luc_name'][0] . '</h3>';
    }
    if( isset( $custom_fields['luc_description'] ) ) {
         $content .= '<p> ' . $custom_fields['luc_description'][0] . '</p>';
    }
    if( isset( $custom_fields['luc_action'] ) ) {
         $content .= '<a href=" ' . $custom_fields['luc_link'][0] . ' ">' . $custom_fields['luc_action'][0] . '</a>';
    }
    $content .= '</div>';

    return $content;
} 

if( is_page() ) {
add_filter( 'the_content', 'luc_add_cutom_fields_to_content' );
}
3
  • You are trying to use is_page() too early while not ready yet. Use this add_filter( 'the_content', function($c){ return is_page() ? luc_add_cutom_fields_to_content($c) : $c; });
    – Ismail
    Nov 23, 2016 at 17:52
  • 1
    @SamuelElh It works !!! please post you answer
    – DCdesign
    Nov 23, 2016 at 19:14
  • Happy to hear. Just did :)
    – Ismail
    Nov 23, 2016 at 19:32

2 Answers 2

2

is_page() requires WP_Query to be initialized and I assume your code runs before this. You can use this function within the filter callback instead:

add_filter('the_content', function($c){
    return is_page() ? luc_add_cutom_fields_to_content($c) : $c;
});
0

Maybe the filter is firing well, but There is no global scope for the current post and the if(isset(...)) can't be execute.

At the top of the function, you can do it with get_post_meta()

 global $post;

 $custom_fields = get_post_meta($post->ID);
1
  • Don´t work ... function luc_add_cutom_fields_to_content( $content ) { global $post; $custom_fields = get_post_meta($post->ID);
    – DCdesign
    Nov 23, 2016 at 19:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.