
本文旨在解决WordPress Elementor Pro中,根据作者元数据(如城市、风格、最高级别等)是否存在来动态显示特定内容的问题。通过修改代码,使用get_the_author_meta函数分别获取各项元数据,并结合“OR”运算符判断是否显示预设的提示信息,从而实现更灵活的作者信息展示。
在WordPress中使用Elementor Pro构建作者页面时,经常需要根据作者是否填写了某些元数据来动态显示不同的内容。例如,如果作者没有填写城市、风格或最高级别等信息,则显示一个默认的提示信息。本文将介绍如何通过修改代码来实现这一功能。
问题分析
核心问题在于,get_the_author_meta函数一次只能获取一个元数据的值。如果尝试一次性获取多个元数据,则无法正确判断每个元数据是否为空。
解决方案
解决方案是分别调用get_the_author_meta函数获取每个元数据的值,然后使用逻辑“OR”运算符判断是否显示提示信息。
立即学习“前端免费学习笔记(深入)”;
以下是修改后的代码示例:
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 );
登录后复制
代码解释:
- get_the_author_meta(‘city’, $author_id): 获取作者ID为 $author_id 的 city 元数据。
- empty($author_city) || empty($author_style_of_play) || empty($author_highest_division): 使用 empty() 函数检查每个元数据是否为空。 || (OR) 运算符表示只要其中一个元数据为空,整个条件就为真。
- : 如果上述条件为真,则动态插入CSS样式,将 ID 为 profile_info_template 的元素的 display 属性设置为 inline-block !important,使其显示。
简化代码
如果不需要在其他地方使用这些元数据的值,可以将 get_the_author_meta 函数直接放在 if 语句中,简化代码:
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 );
登录后复制
注意事项
- 确保 #profile_info_template 元素在HTML中存在,并且默认设置为 display: none。
- !important 声明可以覆盖其他CSS规则,确保样式生效。
- 可以将此代码添加到主题的 functions.php 文件中,或者使用代码片段插件。
- 根据实际情况调整元数据的键名(例如:city、style_of_play、highest_division)。
总结
通过分别获取作者的各项元数据,并使用逻辑“OR”运算符判断是否显示提示信息,可以灵活地控制Elementor Pro构建的作者页面的内容展示。这种方法可以应用于各种需要在WordPress中根据用户元数据动态显示内容的场景。
以上就是根据作者元数据是否存在使用CSS显示部分内容的详细内容,更多请关注php中文网其它相关文章!