1

I have an ACF custom field that depends on the value I need to change the page title, however, I cannot affect the page title, it appears my code is running after the page title is generated.

To explain my requirements. This is a real estate site where some listings are confidential, they flag it as such in the admin, the frontend should only show a small amount of data to logged out users.

Heres the latest code ive tried:

add_filter('init', 'my_custom_title');
function my_custom_title( $title ){
    global $post;
    //var_dump($post);
    echo $post->ID;
    $hide_price = get_field("hide_price");
    echo get_field("beds",$post->ID);
    $view_hidden = get_field('view_hidden_listings', 'user_'. get_current_user_id() );
    if($view_hidden == 1) {
        $hide_price = 0;
    }
    if( $post->post_type == 'sales_listings' && $hide_price == 1) {
        return "Confidential";
    }
    echo $view_hidden;
}

Any help is greatly appreciated, I've been requesting support from the ACF guys but they are unable to help.

Thanks!

2
  • Are you referring to the page title in the <title> tag or the displayed page title on the page? Also don't see a return for the my_custom_title function. Those two questions will effect how you'd want to approach this. – josh.chavanne Nov 29 '17 at 18:20
  • If this is not for the HTML title tag then your better approach will be in your template to make this modification. – Drupalizeme Nov 29 '17 at 18:38
2

If you refer to the post title you need to hook your function to the_title filter like explained in the codex.

add_filter('the_title', 'my_custom_title', 10, 2);

If you refer to the HTML meta in your page then you need to hook your function to document_title_parts filter explained here.

add_filter('document_title_parts', 'my_custom_title', 10, 2);

The two filters work differently as the first passes the title as a string and the second an array which contains the title as well. So depending on which one you need your code will need to be adapted to work accordingly.

If you can explain better your needs a better answer can be given.

1

In order to change the title, you need to use the_title filter, also if you want to determine if the user is logged in or not just use is_user_logged_in() function.

function my_custom_title( $title, $id = null ) {
    global $post;
    if( $post->post_type == 'sales_listings' && !is_user_logged_in() ) {
        $title =  "Confidential";
    } 
    return $title;
}
add_filter( 'the_title', 'my_custom_title', 10, 2 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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