Products
GG网络技术分享 2025-03-18 16:16 0
在默认情况下,WordPress 不会直接执行 PHP 代码来显示侧边栏小部件。这是因为为了安全性和性能方面的考虑,WordPress 通常不允许在文章内容、小部件或主题文件中执行任意 PHP 代码。
但是,您可以使用以下方法在 WordPress 侧边栏中嵌入 PHP 代码:
1. 使用插件: 有一些插件可用于启用在小部件中执行 PHP 代码。其中一个流行的插件是 "PHP Code Widget"。安装并启用此插件后,您可以在小部件区域中添加 "PHP Code" 小部件,然后在其中嵌入 PHP 代码。这允许您在侧边栏中执行自定义 PHP 代码。
2. 创建自定义小部件: 如果您具有编程技能,可以创建一个自定义小部件,该小部件允许执行 PHP 代码。以下是一个简单的示例,展示如何创建一个自定义小部件:
a. 在您的主题文件夹中创建一个新文件,例如 `custom-php-widget.php`。
b. 在 `custom-php-widget.php` 文件中添加以下代码:
<?phpclass Custom_PHP_Widget extends WP_Widget {
function __construct() {
parent::__construct(
'custom_php_widget',
'Custom PHP Widget',
array('description' => 'A widget for executing custom PHP code.')
);
}
public function widget($args, $instance) {
echo $instance['php_code'];
}
public function form($instance) {
$php_code = isset($instance['php_code']) ? esc_attr($instance['php_code']) : '';
?>
<p>
<label for="<?php echo $this->get_field_id('php_code'); ?>">PHP Code:</label>
<textarea class="widefat" id="<?php echo $this->get_field_id('php_code'); ?>" name="<?php echo $this->get_field_name('php_code'); ?>"><?php echo $php_code; ?></textarea>
</p>
<?php
}
public function update($new_instance, $old_instance) {
$instance = array();
$instance['php_code'] = $new_instance['php_code'];
return $instance;
}
}
function register_custom_php_widget() {
register_widget('Custom_PHP_Widget');
}
add_action('widgets_init', 'register_custom_php_widget');
?>
WordPress主题制作调用作者的函数,最常见的是调用作者,不调用其他信息;制作的WordPress主题比较复杂,又或是有特殊的需求,需要调用关于作者的更多信息,以下关于作者信息调用的17个函数,值得推荐学习。
<?php the_author(); ?> //显示文章的作者<?php the_author_description(); ?> //显示文章作者的描述(作者个人资料中的描述)
<?php the_author_login(); ?> //显示文章作者的登录名
<?php the_author_firstname(); ?> //显示文章作者的firstname(名)
<?php the_author_lastname(); ?> //显示文章作者的lastname(姓)
<?php the_author_nickname(); ?> //显示文章作者的昵称
<?php the_author_ID(); ?> //显示文章作者的ID号
<?php the_author_email(); ?> //显示文章作者的电子邮箱
<?php the_author_url(); ?> //显示文章作者的网站地址
<?php the_author_link (); ?> //(添加于2.1版本) 显示一个以文章作者名为链接名,链接地址为文章作者的网址的链接。
<?php the_author_icq(); ?> //(不推荐使用) 显示文章作者的icq
<?php the_author_aim(); ?> //显示文章作者的aim
<?php the_author_yim(); ?> //显示文章作者的yim
<?php the_author_msn(); ?> //(不推荐使用) 显示文章作者的msn
<?php the_author_posts(); ?> //显示文章作者已发表文章的篇数
<?php the_author_posts_link(); ?> //显示一个链接到文章作者已发表文章列表的链接
<?php list_authors(); ?> //(不推荐使用) 显示blog所有作者和他们的相关信息。
如下:
<?php wp_list_authors(); ?> //显示blog作者列表
如果作者发表过文章,则他的名字将链接到他发表的文章列表中。可定义是否显示其他信息。
参数:
optioncount:是否显示各个作者发表文章数,可选值:true 和 false(默认值)
exclude_admin:是否不显示”admin”用户,可选值:true(默认值) 和 false
show_fullname:是否显示各个作者的全名,如果不显示,将显示昵称。可选值:true 和 false(默认值)
hide_empty:是否不显示发表文章数为0的作者,可选值:true(默认值) 和 false
feed:链接到各个作者发表文章的RSS供稿种子链接名,默认为空,不显示RSS供稿种子
feed_image:供稿种子的图片地址,如果提供此项,则覆盖上面的feed,默认为空。Demand feedback