The plugin generated xxx characters of unexpected output during activation [duplicate] - php

This question already has answers here:
The plugin generated X characters of unexpected output during activation (WordPress)
(25 answers)
Closed 4 years ago.
I am creating WordPress plugin to display Total Twitter counter & Feed Subscriber. You can manage it via widget.
I am getting this error.
The plugin generated 123 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.
<?php
/*
* Plugin Name: Twitter & RSS Stats
* Version: 1.0
* Plugin URI: http://sss.com/
* Description: Facebook, Twitter & RSS Social Stats widget tutorial.
* Author: Ajay Patel
* Author URI: http://sss.com/
*/
addHeaderCode();
function addHeaderCode() {
echo '<link type="text/css" rel="stylesheet" href="' . get_bloginfo('wpurl') . '/wp-content/plugins/TRR_Stats/css/style.css" />' . "\n";
}
/*******************************/
/* Create table */
/********************************/
function my_plugin_create_table()
{
// do NOT forget this global
global $wpdb;
// this if statement makes sure that the table doe not exist already
if($wpdb->get_var("show tables like TRR_Stats") != 'TRR_Stats')
{
$sql = "CREATE TABLE TRR_Stats (
id mediumint(9) NOT NULL,
rss_email tinytext NOT NULL,
twitter tinytext NOT NULL,
rss tinytext NOT NULL,
UNIQUE KEY id (id)
);";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
}
// this hook will cause our creation function to run when the plugin is activated
register_activation_hook( __FILE__, 'my_plugin_create_table' );
class FTRWidget extends WP_Widget
{
/**
* Declares the FTRWidget class.
*
*/
function FTRWidget(){
$widget_ops = array('classname' => 'widget_hello_world', 'description' => __( "Example widget demoing WordPress 2.8 widget API") );
$control_ops = array('width' => 300, 'height' => 300);
$this->WP_Widget('helloworld', __('Twitter & RSS Social Stats'), $widget_ops, $control_ops);
}
/**
* Displays the Widget
*
*/
function widget($args, $instance){
extract($args);
$rss_email = empty($instance['rss_email']) ? 'webdesignergeeks' : $instance['rss_email'];
$twitter = empty($instance['twitter']) ? 'webdesignergeek' : $instance['twitter'];
$rss = empty($instance['rss']) ? 'webdesignergeeks' : $instance['rss'];
# Featch Data from table
global $wpdb;
$item_info = $wpdb->get_row("SELECT * FROM TRR_Stats WHERE id=1;");
$rss_email_f = $item_info->rss_email;
$url = file_get_contents('https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=24thfloor');
preg_match( '/circulation="(\d+)"/', $url, $matches );
if ( $matches[1] )
$rss_f = $matches[1] . " Subscribers";
else
echo "0";
$twit = file_get_contents('http://twitter.com/users/show/'.$twitter.'.xml');
preg_match( '/\<followers_count\>(\d+)\<\/followers_count\>/', $twit, $matches );
if ( $matches[1] )
$twitter_f = $matches[1] . " Followers";
else
$twitter_f = "0";
echo '
<div class="sidebarContainer" id="sidebarSubscribe">
<a target="_blank" href="http://twitter.com/'.$twitter.'" class="subscribeSidebarBox" id="followTwitter">
<span class="icon"><img src="'.get_bloginfo('url').'/wp-content/plugins/TRR_Stats/img/twitter.png" alt="Twitter" /></span>
<span class="title">Follow Us on Twitter</span>
<span class="count">'.$twitter_f.'+</span>
</a>
<a target="_blank" href="http://feeds.feedburner.com/'.$rss.'" class="subscribeSidebarBox" id="subscribeRSS">
<span class="icon"><img src="'.get_bloginfo('url').'/wp-content/plugins/TRR_Stats/img/rss_feed.png" alt="RSS"/></span>
<span class="title">Subscribe to our RSS feed</span>
<span class="count">'.$rss_f.'+</span>
</a>
<a target="_blank" href="http://feedburner.google.com/fb/a/mailverify?uri='.$rss_email_f.'" class="subscribeSidebarBox" id="subscribeEmail">
<span class="icon"><img src="'.get_bloginfo('url').'/wp-content/plugins/TRR_Stats/img/rss_email.png" alt="rss_email" /></span>
<span class="title">Subscribe for updates via</span>
<span class="count">EMAIL</span>
</a>
</div>';
# After the widget
echo $after_widget;
}
/**
* Saves the widgets settings.
*
*/
function update($new_instance, $old_instance){
$instance = $old_instance;
$instance['rss_email'] = strip_tags(stripslashes($new_instance['rss_email']));
$instance['twitter'] = strip_tags(stripslashes($new_instance['twitter']));
$instance['rss'] = strip_tags(stripslashes($new_instance['rss']));
global $wpdb;
//Insert First time
$wpdb->insert( 'TRR_Stats', array(
'id' => 1,
'rss_email' => $instance['rss_email'],
'twitter' => $instance['twitter'],
'rss' => $instance['rss']
)
);
//Rest Update Data
global $wpdb;
$wpdb->update( 'TRR_Stats',
array(
'rss_email' => $instance['rss_email'],
'twitter' => $instance['twitter'],
'rss' => $instance['rss']
),
array(
'id' => 1
)
);
return $instance;
}
/**
* Creates the edit form for the widget.
*
*/
function form($instance){
//Defaults
$instance = wp_parse_args( (array) $instance, array('rss_email'=>'', 'twitter'=>'engiguide', 'rss'=>'www.rss_email.com/engiguide') );
$rss_email = htmlspecialchars($instance['rss_email']);
$twitter = htmlspecialchars($instance['twitter']);
$rss = htmlspecialchars($instance['rss']);
# Output the options
# Twitter
echo '<p style="text-align:right;"><label for="' . $this->get_field_name('twitter') . '">' . ('Twitter:') . ' <input style="width: 200px;" id="' . $this->get_field_id('twitter') . '" name="' . $this->get_field_name('twitter') . '" type="text" value="' . $twitter . '" /></label></p>';
echo '<p style="padding-left: 110;">i.e: webdesignergeeks</p>';
# Rss
echo '<p style="text-align:right;"><label for="' . $this->get_field_name('rss') . '">' . __('Rss:') . ' <input style="width: 200px;" id="' . $this->get_field_id('rss') . '" name="' . $this->get_field_name('rss') . '" type="text" value="' . $rss . '" /></label></p>';
echo '<p style="padding-left: 110;">i.e: webdesignergeeks</p>';
# Rss Email
echo '<p style="text-align:right;"><label for="' . $this->get_field_name('rss_email') . '">' . ('Rss Email:') . ' <input style="width: 200px;" id="' . $this->get_field_id('rss_email') . '" name="' . $this->get_field_name('rss_email') . '" type="text" value="' . $rss_email . '" /></label></p>';
echo '<p style="padding-left: 110;">i.e: webdesignergeeks</p>';
}
}// END class
/**
*
* Calls 'widgets_init' action after the Hello World widget has been registered.
*/
function TTRInit() {
register_widget('FTRWidget');
}
add_action('widgets_init', 'TTRInit');
?>

I got extra "xxx" white spaces after the final php closing tag. Removed it and the warning is gone. Those white spaces were the "unexpected output".

Remove space from start of tags. remove addHeaderCode(); from top and add this code add_action('wp_head', 'addHeaderCode'); to your file after addHeaderCode() function. its definitely resolve your problem.

it was a UTF8 related issue. I converted it with Notepad++ in UTF8 but I had to conert it in "UTF8 (without BOM)".
Now I don't have any notice.

You should try this:
remove white spaces
run function plugin_error()
in wp_config.php file set wp_DEBUG true , that will help you to see errors
This might help you.

I don't think you should be sending any output in addHeaderCode(), this occurs far too early. See Actions Run During a Typical Request.
Instead, try hooking to wp_head to add your stylesheet, which should be triggered between <head>...</head>.

Try wrapping the message with __() like __("Hello, world!") did the trick for me.

You can remove update() function without this function it will work fine and will do same thing you are doing.

I had the same issue with WooCommerce Smart Coupons plugin. I removed all extra new lines from plugin php files and saved them in "UTF8 (without BOM)" (as #Umaie Hamid mentioned). This fixed the issue.

I've fixed this by removing the spaces in the code using the "edit plugin" in the WP admin. I think when WP save the changes it also does all the necessary settings like saving the file as UTF-8.

I Was getting same error just remove white spacing in your code.

Related

How to Access Author Meta (get_the_author_meta) in wp_head

I'm trying to write my own code for populating JSON-LD Schema code (I'd rather not rely on plugins for this).
For Wordpress posts, one of the key schema elements is author data. So I use get_the_author_meta() function to access it.
This works perfectly fine when it fires in the wp_footer action, but comes up empty when firing in wp_head.
I've checked this in the astra theme as well as twentytwentyone theme.
I stole this code just for demonstration purposes, it's twitter OG card and not Schema but its effectively the same. Forgive me but I can't remember what stackoverlow post I found it in.
In functions.php:
function my_twitter_cards() {
if (is_singular()) {
global $post;
$twitter_user = get_the_author_meta('nickname'); #This is the element that works in wp_footer but not in wp_head, all the other fields seem to work.
$twitter_url = get_permalink();
$twitter_title = get_the_title();
$twitter_excerpt = get_the_excerpt();
$twittercard_image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full');
$twittercard_thumb = $twittercard_image[0];
if (!$twittercard_thumb) {
$twittercard_thumb = 'https://www.example.com/default-image.png';
}
if ($twitter_user) {
echo '<meta name="twitter:creator" value="#' . esc_attr($twitter_user) . '" />' . "\n";
}
echo '<meta name="twitter:card" value="summary" />' . "\n";
echo '<meta name="twitter:url" value="' . esc_url($twitter_url) . '" />' . "\n";
echo '<meta name="twitter:title" value="' . esc_attr($twitter_title) . '" />' . "\n";
echo '<meta name="twitter:description" value="' . esc_attr($twitter_excerpt) . '" />' . "\n";
echo '<meta name="twitter:image" value="' . esc_url($twittercard_thumb) . '" />' . "\n";
echo '<meta name="twitter:site" value="#mhthemes" />' . "\n";
}
}
add_action('wp_head', 'my_twitter_cards'); #swap this out for wp_footer to see the difference.
My theory was that it couldn't access the loop when called in the header, but that doesn't explain why post-specific data is populating (i.e permalink, title, etc), and not the get_the_author_meta data.
Now I can go with it if I just populate the footer, in this application it would be OK, but some things need to be in the header, so I want to figure out why its not working as expected.
Thank you in advance!
get_the_author_meta() accepts two optional parameters:
get_the_author_meta(string $field = '', int|false $user_id = false)
Where $field is the user field to retrieve (Default value is '')
and $user_id is the user ID (Default value is false)
When used within The Loop, the user ID need not be specified, it defaults to the current post author. A user ID must be specified if used outside The Loop.
You can get the current post author ID outside The Loop, and then use it to fetch the desired author field like this:
global $post;
$post_id = $post->ID;
$post_author_id = get_post_field('post_author', $post_id);
$twitter_user = get_the_author_meta('nickname', $post_author_id);
On a side note, the above example uses global $post because you are already using it in your code, otherwise I would use get_queried_object_id() to get the post ID outside of The Loop:
$post_id = get_queried_object_id();

Use an external Link as the WordPress profile picture

I want to write a Single Sign On (SSO) plugin for WordPress. I want to use an external image link as user's profile picture after user login.
This image has a link which is located in http://www.example.com/image.png.
How can I do this in WordPress?
Please add this code to your activated theme's functions.php file.
add_filter( 'author_link', 'modify_author_link', 10, 1 );
function modify_author_link( $link ) {
$link = 'http://google.com/';
return $link;
}
You can use your any link, just change https://google.com to your link.
Thanks.
These Hooks ('get_avatar', 'avatar_defaults') are also available by WordPress, as an example:
you can check the documentation here:
https://codex.wordpress.org/Function_Reference/get_avatar
function my_custom_avatar($avatar, $id_or_email, $size, $default, $alt)
{
echo $avatar . ' -> ' . $id_or_email . ' -> ' . $size . ' -> ' . $default . ' -> ' .$alt;
$avatar = 'https://www.example.com/yourImage';
$avatar = "<img alt='{$alt}' src='{$avatar}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />";
return $avatar;
}
add_filter( 'get_avatar', 'my_custom_avatar', 10, 5 );
add_filter( 'avatar_defaults', 'my_custom_avatar', 10, 1 );```

buddy press profile link not going to correct place

I created a bp-custom.php and regrouped the menu items fine. But now i am trying to add a link to go to /site/members. It list all the members.
When i add it though it goes under the profile I am viewing. I am redirecting to a wordpress page if that helps. Or is there a better way to do this.
Ex :
http://website.com/log-in/members/username/members/
I want it to go just here
http://website.com/log-in/members/
I would love to learn how to just put a url and no slug but whatever works. I do not know why it keeps referencing that signed in /member/username. I have even tried parent url and that did not work. I might have been using parent url syntax wrong.
Here is the function
function mb_bp_profile_menu_posts() {
global $bp;
bp_core_new_nav_item(
array(
'name' => 'Members',
'slug' => 'members',
'position' => 60,
)
);
}
I know that i can create .htaccess for this. But I don't want to do it.
May i know what is the clean way (alternate way) to do this?
I have tried what the user said in comment below and found in bp-members-template this function. I then added the part in bold to add the link but that did not work. I am just adding a google link for testing only.
function bp_get_displayed_user_nav() {
global $bp;
foreach ( (array) $bp->bp_nav as $user_nav_item ) {
if ( empty( $user_nav_item['show_for_displayed_user'] ) && !bp_is_my_profile() )
continue;
$selected = '';
if ( bp_is_current_component( $user_nav_item['slug'] ) ) {
$selected = ' class="current selected"';
}
if ( bp_loggedin_user_domain() ) {
$link = str_replace( bp_loggedin_user_domain(), bp_displayed_user_domain(), $user_nav_item['link'] );
} else {
$link = trailingslashit( bp_displayed_user_domain() . $user_nav_item['link'] );
}
echo apply_filters_ref_array( 'bp_get_displayed_user_nav_' . $user_nav_item['css_id'], array( '<li id="' . $user_nav_item['css_id'] . '-personal-li" ' . $selected . '><a id="user-' . $user_nav_item['css_id'] . '" href="' . $link . '">' . $user_nav_item['name'] . '</a></li>', &$user_nav_item ) );
**echo "<a href='http://www.google.com'>Google</a>"; }**
}
The bp_core_new_nav_item function is used to add a link to the user's navigation which explains why you're seeing URLs like /members/username/members/ when clicking on the tab. I don't think bp_core_new_nav_item is the right approach here.
An alternative approach would be to replace the function in your theme template that outputs the navigation with your own custom menu.
See this article on the BP Template Hierarchy which shows you how you can set up your own templates:
http://codex.buddypress.org/themes/theme-compatibility-1-7/template-hierarchy/

PHP Mixing html and code

(Preamble: Am new to PHP, coming from a C# background where I am used to very clean code. Am currently working on my own Wordpress site which has a purchased theme.)
I have seen this type of code in a WordPress theme:
<img src="<?php echo esc_url( $logo ); ?>" alt="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>" id="logo"/>
I find this very hard to read compared to the refactored:
<?php
echo '<a href="';
echo esc_url( home_url( '/' ) );
echo "><img src=";
echo esc_url( $logo );
echo " alt=";
echo esc_attr( get_bloginfo( 'name' ) );
echo '" id="logo"/></a>'
?>
But this is the easiest by far:
<?php
get_anchor($url, $imgsource, $alt, $id);
?>
get_anchor being a custom function that echos an anchor configured according to the parameters.
But surely I am not the first to think of this. Are there any existing libs that have a set of functions that return properly formatted html like in this example? Is there something I am missing?
I've written a function that returns a HTML tag based on the pure PHP output:
function tag($name, $attrs, $content) {
$res = '';
$res .= '<' . $name;
foreach($attrs as $key => $val)
$res .= ' ' . $key . '="' . $val . '"';
$res .= isset($content) ? '>' . $content . '</'.$name.'>' : ' />';
return $res;
}
$name is the tagname (e.g. a)
$attrs is a key, value array with attributes (e.g. array('href','http://google.com/'))
$content is the content / body of the tag (an other element or text)
Example basic use:
echo tag('a', array('href' => 'http://google.com/'),'Google');
Example nested use with multiple children:
echo tag('ul',array(),
tag('li',array(),'one') .
tag('li',array(),'two') .
tag('li',array(),'three')
);
I believe what you are looking for are templates like Smarty. They are the cleanest way to display information as code and view are completely separated.
However Wordpress do not use them, I don't know why actually, probably because most PHP programmers are not used to it.
Most of the PHP frameworks provide such libraries to out put html through parameterized functions, most of them are part of view layer if the framework follows MVC pattern.
but if you are not using any of the framework then you may use these libraries from here
PHP Pear Packages
And for building forms in particular see
HTML_QuickForm2

WordPress types plugin getting post's title instead of image's title

I'm using a wordpress plugin called Types.
I'm using their custom field capabilities to upload images into my gallery in my custom sidebar. I'm also using a lightbox to display these images.
So I'm trying get the title of each image to appear
<?php $resortimages = get_post_meta(get_the_ID(), 'wpcf-r-images');
foreach ($resortimages as $resortimage) {
echo '<li><a href="'. $resortimage. '" rel="lightbox" title="" ><img src="'. $resortimage. '"/></a></li>';
}
I've tried getting post title but it just gets the title of the post itself.
Jesper, it looks like Types image field only stores image URL, not its contents. If you want to retrieve some other info (title, caption and description, for example), probably you'll have to try to get image ID by its URL. In your functions.php:
/**
* Retrieve the attachment ID from its URL
*
* #param string $image_url
* #return int $attachment[0] The attachment ID
*
* #link http://pippinsplugins.com/retrieve-attachment-id-from-image-url/
*/
function mytheme_get_attachment_id( $image_url ) {
global $wpdb;
$prefix = $wpdb->prefix;
$attachment = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM " . $prefix . "posts" . " WHERE guid='%s';", $image_url ) );
return $attachment[0];
}
After that, you can use you foreach and check for your IDs:
<?php
$resortimages = get_post_meta(get_the_ID(), 'wpcf-r-images');
foreach ($resortimages as $resortimage) {
// Get attachment ID by its URL
if ( $resortid = mytheme_get_attachment_id( $resortimage ) )
$resortname = get_the_title($resortid);
echo '<li><a href="'. $resortimage. '" rel="lightbox" title="' . $resorttitle . ' ><img src="'. $resortimage. '"/></a></li>';
}
?>
But beware of the number of queries that you'll do. Hope it helps!

Categories