致命错误:WP抱怨重新声明

时间:2016-08-11 作者:Henrique Almeida Marcomini

我正在制作一个包含多个文件的插件,它与wpdb有一些交互,所以我将所有内容都放在一个名为FA db的文件中。php

<?php
global $wpdb;
function FAvideoid()
{
    return $wpdb->get_var( "SELECT \'video_id\' FROM $wpdb->ytvideos ORDER BY RAND() LIMIT 1;");
}
function FAregister($id)
{
    $wpdb->insert( \'ytvideos\', $id, \'%s\' );
}

function FAsetup()
{
    $table_name = $wpdb->prefix . "ytvideos"; 
    $charset_collate = $wpdb->get_charset_collate();
    $sql = "CREATE TABLE $table_name ( id mediumint(9) NOT NULL AUTO_INCREMENT, video_id varchar(55) DEFAULT \'\' NOT NULL, UNIQUE KEY id (id))     $charset_collate;";
    dbDelta( $sql );
}
?>
并将其包含在我的主文件中

<?php
/*
Plugin Name: Floating Ads
Description: A floating ad that have youtube ads built in
Version: 0.5.0
Author: Henrique Almeida Marcomini
*/
include "FA-db.php";
include "FA-admin.php";
include "FA-ad.php";
add_action( \'admin_menu\', \'FAmenu\' );
add_action( \'wp\', \'FAad\' );
add_action( \'activated_plugin\', \'FAsetup\' );  
?>
我不把它包括在其他地方。

但是当我尝试激活插件时,我得到了以下错误

Fatal error: Cannot redeclare FAvideoid() (previously declared in /home/u696621553/public_html/wp-content/plugins/FloatingAds/FA-db.php:7) in /home/u696621553/public_html/wp-content/plugins/FloatingAds/FA-db.php on line 8

1 个回复
最合适的回答,由SO网友:jgraup 整理而成

将函数包装为!function_exists() 以避免重新声明错误。

if( ! function_exists(\'FAvideoid\') ) :

  function FAvideoid()
  {
      return $wpdb->get_var( "SELECT \'video_id\' FROM $wpdb->ytvideos ORDER BY RAND() LIMIT 1;");
  }

endif;
或者为了减少代码被多次导入:

include_once "FA-db.php";
include_once "FA-admin.php";
include_once "FA-ad.php";
但最好的方法可能是将两者结合起来:

// Only load files and hook events if your functions haven\'t been defined

if( ! function_exists(\'FAvideoid\') ) :

    include_once "FA-db.php";
    include_once "FA-admin.php";
    include_once "FA-ad.php";

    add_action( \'admin_menu\', \'FAmenu\' );
    add_action( \'wp\', \'FAad\' );
    add_action( \'activated_plugin\', \'FAsetup\' );

endif;