
本文旨在解决 WordPress 中,在使用 Elementor Pro 构建作者页面时,如何根据作者元数据的存在与否,动态地显示或隐藏特定的 Section。核心方法是利用 get_the_author_meta 函数获取作者信息,并结合 CSS 的 display 属性进行控制,从而实现更灵活的页面展示效果。
在 WordPress 中,我们经常需要根据作者的元数据来定制页面显示,例如,当作者没有填写某些信息时,显示一个默认的提示信息。本文将详细介绍如何使用 CSS 和 WordPress 函数来实现这一功能,尤其是在使用 Elementor Pro 构建页面时。
WordPress 提供了 get_the_author_meta 函数来获取作者的元数据。该函数接受两个参数:元数据的键名和作者 ID。需要注意的是,get_the_author_meta 函数一次只能获取一个元数据的值。
get_the_author_meta( string $field = '', int $user_id = 0 )
我们的目标是:如果 city、style_of_play 和 highest_division 这三个作者元数据都为空,则显示一个名为 profile_info_template 的 Section。默认情况下,这个 Section 的 display 属性设置为 none。
立即学习“前端免费学习笔记(深入)”;
为了实现这个逻辑,我们需要分别获取这三个元数据的值,然后使用 PHP 的 empty 函数判断它们是否为空。如果都为空,则通过内联 CSS 将 profile_info_template 的 display 属性设置为 inline-block。
以下是实现该功能的代码示例:
function nothing_to_show_display(){
global $post;
$author_id = $post->post_author;
$author_city = get_the_author_meta('city', $author_id);
$author_style_of_play = get_the_author_meta('style_of_play', $author_id);
$author_highest_division = get_the_author_meta('highest_division', $author_id);
if(empty($author_city) || empty($author_style_of_play) || empty($author_highest_division)) : ?>
<style type="text/css">
#profile_info_template {
display: inline-block !important;
}
</style>;
<?php endif;
}
add_action( 'wp_head', 'nothing_to_show_display', 10, 1 );代码解释:
如果不需要在其他地方使用这些元数据的值,可以直接在 if 语句中使用 get_the_author_meta 函数,从而简化代码:
function nothing_to_show_display(){
global $post;
$author_id = $post->post_author;
if(empty(get_the_author_meta('city', $author_id)) || empty(get_the_author_meta('style_of_play', $author_id)) || empty(get_the_author_meta('highest_division', $author_id))) : ?>
<style type="text/css">
#profile_info_template {
display: inline-block !important;
}
</style>;
<?php endif;
}
add_action( 'wp_head', 'nothing_to_show_display', 10, 1 );通过本文,你学习了如何在 WordPress 中,使用 get_the_author_meta 函数获取作者元数据,并结合 CSS 的 display 属性,动态地显示或隐藏页面 Section。这种方法可以让你更灵活地定制作者页面,并提供更好的用户体验。记住,get_the_author_meta 一次只能获取一个元数据的值,因此需要分别调用该函数来获取不同的元数据。同时,根据实际情况选择合适的代码实现方式,并注意性能优化。
以上就是使用 CSS 在 WordPress 中根据作者元数据有无显示 Section的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号