1

I'm creating a WordPress Widget for show name of advertiser.

When I try to activate the plugin a error

The plugin generated 3 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.

I did these things:

1- remove white space before or after the PHP opening or closing tags

2- change encoding to UTF8-BOM

<?php
class adsMain extends WP_Widget {

    public function __construct() {

        parent::__construct(
            'adsMain',
            __( 'تبلیغات', 'text' ),
            array(
                'classname'   => 'adsMain',
                'description' => __( 'برای ایجاد تبلیغات جدید این کادر را به مکان دلخواه خود بکشید.', 'text' )
            )
        ); 
    }
    /**  
     * Front-end display of widget.
     *
     * @see WP_Widget::widget()
     *
     * @param array $args     Widget arguments.
     * @param array $instance Saved values from database.
     */
    public function widget( $args, $instance ) {

        extract( $args );

        $advertiser = apply_filters( 'widget_title', $instance['advertiser'] );

        echo $advertiser;

    }

    /**
      * Sanitize widget form values as they are saved.
      *
      * @see WP_Widget::update()
      *
      * @param array $new_instance Values just sent to be saved.
      * @param array $old_instance Previously saved values from database.
      *
      * @return array Updated safe values to be saved.
      */
    public function update( $new_instance, $old_instance ) {

        $instance = $old_instance;

        $instance['advertiser'] = strip_tags( $new_instance['advertiser'] );

        return $instance;

    }

    /**
      * Back-end widget form.
      *
      * @see WP_Widget::form()
      *
      * @param array $instance Previously saved values from database.
      */
    public function form( $instance ) {

        $advertiser = ( isset($instance['advertiser']) ? esc_attr ( $instance['advertiser'] ) : '' );
?>

        <p>
            <label for="<?php echo $this->get_field_id('advertiser'); ?>"><?php _e('نام شخص / شرکت تبلیغ دهنده:'); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id('advertiser'); ?>" name="<?php echo $this->get_field_name('advertiser'); ?>" type="text" value="<?php echo $advertiser; ?>" />
        </p>
<?php
    }

}

/* Register uploader */
add_action ('admin_enqueue_scripts', function () {
    wp_register_script('adsMain-script' , plugins_url( '/js/adsMain-script.js', __FILE__ ), array( 'jquery' ), '20160904', true );
    wp_enqueue_script('adsMain-script');
    wp_enqueue_media();
});

/* Register the widget */
add_action('widgets_init', function() {
     register_widget( 'adsMain' );
});
?>
  • 2
    try in UTF-8 without BOM – mmm Sep 4 '16 at 8:41
  • @mmm please include your comment as an answer and try to add some explanation why you thought this would work. – cjbj Sep 4 '16 at 14:53
  • If you are using a debugger, then put a breakpoint around in the activate_plugin method in wordpress/wp-admin/includes/plugin.php. The content of the $output variable might show you the data loaded into the Exception invariably being thrown, and then obfuscated by Wordpress. – Todd Holmberg Feb 1 '17 at 22:09
0

What is BOM?

The UTF-8 byte order mark or simply UTF-8 BOM is a series of bytes that helps the reader to understand the encoding of the current document.

These 3 bytes are:

EF BB BF

Or simply the Unicode character : U+FEFF

In a plugin file encoded as BOM, these bytes will be output when the template is called, causing early output in header, that triggers a common error:

The plugin generated X characters of unexpected output during activation.

This can also happen to theme's files. Since using BOM for UTF-8 files is not recommended by Unicode Standards, you can save your templates as UTF-8 without BOM.

You will also notice that every UTF-8 file that is encoded under BOM has at least a size of 3 bytes, even if it's empty.

0

i have a same issue in my code

<?php
ob_start();
/*
    Plugin Name: User Detail
    Description: Simple 
    Author: varun
    Version: 1.4
*/?>

<?php 
$request_uri = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH );
$is_admin = strpos( $request_uri, '/wp-admin/' );
$qs = $_SERVER['QUERY_STRING']; 
parse_str($qs);
add_action( 'wp_loaded', function () {
if ( is_admin() ) {
        ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" crossorigin="anonymous"></script>
<style>
    .dataTable thead tr th{ text-align:left; }
</style>
<?php
    add_action("admin_menu","addmenu");
    function addmenu(){
        add_menu_page("banner option", "User Detail", 4, "User-Detail", "User");
        //add_submenu_page("banner-option", "banner1", "banner1", 4, "banner-option-1", "option1");
    }
    function getUserID($user_id)
    {
        $user_meta  = get_userdata($user_id);

        $user_roles = $user_meta->roles;
        return $user_roles[0];
    }

    function User() 
    {
        global $wpdb;
        $results = $wpdb->get_results("SELECT ID, display_name, user_email FROM wp_users ORDER BY display_name desc ");
        $_salespeople_query  = "SELECT * FROM `wp_usermeta` WHERE `meta_value` LIKE '%shop_man%'";
        $_salespeople_result = $wpdb->get_results($_salespeople_query);
        $salespeople_ids     = [];
        foreach ( $_salespeople_result as $key ) {
            $salespeople_ids[] = $key->user_id;
        }
    ?>

    <table class="subscriber-table">

        <thead>
            <tr>
            <th>Name</th>
                <th>Email</th>
                <th>Role</th>
                <th>Account Status</th>
                <th>Action</th>
                <th>Sales Person</th>
                <th>Price List</th>
            </tr>
        </thead>
        <tbody>
            <?php
                for ($i = 0; $i < count($results); $i++) {
                    $user_id        = $results[$i]->ID;
                    $user_info      = get_user_meta($user_id);
                    $assigned_salesperson_ID = $user_info['assigned_salesperson'][0];
                    $account_status = $user_info['account_status'][0];
                    $account_status_display = "InActive";
                    $display_name = $results[$i]->display_name;
                    $user_email   = $results[$i]->user_email;
                    $role         = getUserID($user_id);

                    if ( $role !== 'subscriber' ) {
                        continue;
                    }
                    if ( $role === 'subscriber' ) {
                        $role = "Customer";
                    }
                    if ( $account_status === "approved" ) {
                        $account_status_display = "Active";
                    }
                ?>

                <tr>
                    <form  class="upload_csv" method="post"  enctype="multipart/form-data">
                        <td><?= $display_name; ?> </td>
                        <td><?= $user_email ; ?></td>
                        <td><?= $role; ?></td>
                        <td><?= $account_status_display; ?></td>
                        <td>
                            <select class="account_status_ajx">

                                <?php if ( $account_status === "approved" ) { ?>
                                    <option selected value='<?= $user_id . "_active"; ?>'>Active</option>
                                    <option value='<?= $user_id . "_inActive"; ?>'>InActive</option>
                                    <?php } else { ?>
                                    <option value='<?= $user_id . "_active"; ?>'>Active</option>
                                    <option selected value='<?= $user_id . "_inActive"; ?>'>InActive</option>
                                <?php } ?>

                            </select>
                        </td>
                        <td>
                            <?php 
                            $salespeople_select = "<select class='sales_person_update'>";
                                $salespeople_select .= "<option value='0'>Not Set</option>";

                                foreach ($salespeople_ids as $user_id_sales) {
                                    $user_info = get_user_meta($user_id_sales);

                                    $first_name = ucfirst($user_info['first_name'][0]);
                                    $last_name  = ucfirst($user_info['last_name'][0]);

                                    $full_name = $first_name . " " . $last_name;

                                    $salespeople_select .= "<option value='" . $user_id_sales ."_".$user_id . "'>" . $full_name . "</option>";

                                    if ($user_id_sales === $assigned_salesperson_ID) {
                                        $salespeople_select .= "<option selected value='" . $user_id_sales ."_".$user_id . "'>" . $full_name . "</option>";

                                    }
                                }

                                $salespeople_select .= "</select>";
                                echo $salespeople_select;

                            ?>
                        </td>
                        <td>

                            <!------------label class="col-md-4 control-label" for="singlebutton">Import data</label--------->
                            <?php 
                                global $wpdb;
                                $result = $wpdb->get_row("SELECT * FROM wp_csv WHERE user_id = '".$user_id."' ");
                                if(!empty($result->csv))
                                {
                                    echo '<div class = "csv_name text-info" > Current CSV "'. $result->csv .'"</div>';
                                }
                                // else
                                // {
                                //      echo '<div class = " text-info" >You havent uploaded any file.</div>';
                                // }
                            ?>
                            <!-- <div class="text-info"></div> -->
                            <input type="file" id="csvFile" name="file" style="margin-top:0px; "/> 
                            <input type="hidden" id="ipaddr_<?php echo $user_id ; ?>" name="user_id" value="<?php echo $user_id; ?>">

                            <!-- <input type="submit" name="upload" id="upload" value="Upload csv" class="btn btn-primary" onclick="check_csv()" style =" margin-bottom:10px;"><hr> -->
                            <button onclick="check_csv(<?php echo $user_id ; ?>)" class="btn btn-primary">Upload CSV</button>

                        </td>
                    </form>
                </tr>
                <?php
                } 
            ?>
        </tbody>
    </table>
    <?php }

?>
<script type="text/javascript">


    function check_csv(userid)
    {
        alert(userid);

        event.preventDefault();


        var fd = new FormData();

        var file = jQuery(document).find('input[type="file"]');
        jQuery.each(jQuery(file), function(i, obj) {
            jQuery.each(obj.files,function(j,file){
                fd.append('files[' + j + ']', file);
            })
        });

        fd.append('user_id',userid);
        jQuery.ajax({
            url:"http://159.89.172.50/word_fa/testapi/",
            method:"POST",
            //dataType: 'json',
            enctype: 'multipart/form-data',
            //data:{datakey:formData},
            data:fd,
            //contentType:false,
            //cache:false,
            //processData:false,
            processData: false,
            contentType: false,
            cache: false,
            timeout: 600000,
            success:function(data)
            {
                if(data=='Error1')
                {
                    alert('Invalid file format');
                }
                else if(data == 'Error2')
                {
                    alert('Please Insert a CSV File');
                }

            }
        });
    } 


    jQuery.noConflict()(function($){

        jQuery(document).ready(function() {


            // Initiating DataTable for Subscribers
            $('.subscriber-table').DataTable({"order": [[ 0, "desc" ]]});

            jQuery('body').on('change', '.account_status_ajx', function() {
                let val = jQuery(this).val();
                let split = val.split('_');
                let id = split[0];
                let action = split[1];
                jQuery.ajax({
                    url: 'http://159.89.172.50/word_fa/testapi/?customer_id=' + id + "&action=" + action,
                    type: 'get',
                    success: function(rawResponse) {
                        if ( rawResponse.length > 0 ) {
                            let curLoc = window.location.href;
                            window.location.href = curLoc;
                        }
                    }
                })
            });

            jQuery('body').on('change', '.sales_person_update', function() {

                let val            = jQuery(this).val();
                let split          = val.split('_');
                let salesperson_id = split[0];
                let customer_id    = split[1];
                jQuery.ajax({
                    url: 'http://159.89.172.50/word_fa/testapi/?customer_id=' + customer_id + "&salesperson_id=" + salesperson_id,
                    type: 'get',
                    success: function(rawResponse) {
                        if ( rawResponse.length > 0 ) {
                            let curLoc = window.location.href;
                            window.location.href = curLoc;
                        }
                    }
                })
            });




        }); 
    });
</script>
    <?php
  }
});

?>

if i install this plugin to localhost so its run and not show any message or problem but in server its show header already send i use ob_start but its not work i use wp_encrpyt for CSS and JavaScript but problem occurs any suggestion please.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.