Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

is_admin returning false in backend in server side rendered block #16731

Closed
cre-mer opened this issue Jul 24, 2019 · 1 comment
Closed

is_admin returning false in backend in server side rendered block #16731

cre-mer opened this issue Jul 24, 2019 · 1 comment
Labels
[Package] Server Side Render /packages/server-side-render [Type] Help Request Help with setup, implementation, or "How do I?" questions.

Comments

@cre-mer
Copy link

cre-mer commented Jul 24, 2019

I have a server side rendered block that lists cards with page thumbnails and the title wrapped in a link.
I want that the link only gets a href when I'm in the frontend so I avoid clicking on the cards by mistake in the backend and getting redirected to the card page.
Here is my code:

    $link = is_admin() ? ""
            : " href='" . get_permalink($post->ID) . "'";
                  
    echo <<<CPTItem
        <div class="cpt-list-item"><a class="cpt-list-item__link" $link>
    CPTItem;

Unfortunately is_admin() is returning false in the backend in the block itself. I really don't know why, the only thing I can think about is that it's because the block is server side rendered.
Is there a way around?

@Soean Soean added the [Type] Help Request Help with setup, implementation, or "How do I?" questions. label Jul 24, 2019
@Soean
Copy link
Member

Soean commented Jul 24, 2019

If you have a server side rendered block in the backend, it is rendered via the REST API endpoint /wp/v2/block-renderer/xyz/blockname. This endpoint calls your render function. In the frontend the render function is called directly. The function is_admin() checks if a backend page was requested. In a REST API Request is no backend page, so the function returns false on REST API requests.

Instead you can check, if it is a REST API request via:

if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
    return 'Backend';
} else {
    return 'Frontend';
};

Maybe we should add this info to the support handbook?

@cre-mer I also answered you question here: https://wordpress.stackexchange.com/questions/343583/is-admin-returning-false-in-backend-in-server-side-rendered-block/343592#343592 Please don't post support questions on both platforms.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
[Package] Server Side Render /packages/server-side-render [Type] Help Request Help with setup, implementation, or "How do I?" questions.
Projects
None yet
Development

No branches or pull requests

2 participants