admin管理员组文章数量:1122846
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?
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?
1 Answer
Reset to default 15If 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';
}
Update 2024:
Since WordPress 6.5 you can use the function wp_is_serving_rest_request() which wraps this checks into a function.
if ( wp_is_serving_rest_request() ) {
return 'Backend';
} else {
return 'Frontend';
}
本文标签: phpisadmin returning false in backend in server side rendered block
版权声明:本文标题:php - `is_admin` returning false in backend in server side rendered block 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736293394a1929137.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论