WordPress教程

WordPress通过函数给前端和后台添加自定义字段

阿里云

WordPress 的后台常规页面是填写站点和站点 URL 的位置,我们在自己做网站时,也可以通用 functions.php 按照自己的需要添加自定义的字段。例如我们想在常规页面添加授权码填写框,就可以使用以下的代码,放在 functions.php 代码中。

  1. $new_general_setting = new new_general_setting();
  2. class new_general_setting {
  3. function new_general_setting( ) {
  4. add_filter( 'admin_init' , array( &$this , 'register_fields' ) );
  5. }
  6. function register_fields() {
  7. register_setting( 'general', 'shouquanma', 'esc_attr' );
  8. add_settings_field('fav_color', '<label for="shouquanma">'.__('正版授权码' ).'</label>' , array(&$this, 'fields_HTML') , 'general' );
  9. }
  10. function fields_html() {
  11. $value = get_option( 'shouquanma', '' );
  12. echo '<input type="text" id="shouquanma" name="shouquanma" value="' . $value . '" size="65"/><br><span style="font-size:12px;color:#888">您正在使用<span style="color:#f00">Wordpress正版模板</span>,为保护您的权益和防止模板滥用,请填写<span style="color:#f00">授权码</span>!</span>';
  13. }
  14. }
也想出现在这里?联系我们
创客主机

还可以在后台常规页面添加多个自定义字段

  1. function set_global_seo() {
  2. $global_seo = new GlobalSeo();
  3. $global_seo->setting_fields();
  4. }
  5. add_action( 'admin_init', 'set_global_seo' );
  6.  
  7. class GlobalSeo
  8. {
  9. public function setting_fields()
  10. {
  11. $text_input = [
  12. 'widget_ctextk' => '电话',
  13. 'shouquanma' => '邮箱',
  14. ];
  15. foreach($text_input as $key => $val)
  16. {
  17. $this->sonliss_settings_field($key, $val, 'sonliss_textbox_callback', [$key]);
  18. $this->sonliss_register_setting($key);
  19. }
  20. }
  21. public function sonliss_settings_field($id, $title, $callback, $args)
  22. {
  23. add_settings_field(
  24. $id,
  25. $title,
  26. [ $this, $callback ],
  27. 'general',
  28. 'default',
  29. $args
  30. );
  31. }
  32. public function sonliss_register_setting($id)
  33. {
  34. register_setting('general', $id);
  35. }
  36. public function sonliss_textbox_callback($args) {
  37. $option = get_option($args[0]);
  38. echo '<input type="hidden" data-id="'. $option.'" id="'. $args[0].'" name="'. $args[0] .'" value="" />';
  39. }
  40. }

如果想调用自定义的字段,使用以下的代码来调用:

  1. <?php echo get_option('shouquanma'); ?>

除此之外,我们还可以使用通过 functions.php 给网站后台添加 JS 或者 CSS;

  1. function myfunction_custom_admin_footer2() {
  2. echo '<script src="'.get_template_directory_uri(). '/admin/js/ashuwp_head.js?v=2"></script>';
  3. }
  4. add_filter('admin_footer_text', 'myfunction_custom_admin_footer2');

也可以使用 functions.php 给网站前端添加代码;

  1. function panda_copyright() {
  2. echo '网站前端添加代码';
  3. }
  4. add_action('wp_footer', 'panda_copyright');

在底部模板添加来获取 js 文件。

WordPress 通过函数给前端和后台添加自定义字段

已有 194 人购买
查看演示升级 VIP立刻购买

收藏
(0)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!