PHP QR Code outputting .png as a character string - php

I've built my first WordPress plugin to create a QR Code from a form.
It's just for learning purposes and would not meet standards for commercial release.
However it works perfectly on my local server in WAMP using Twenty Twenty theme.
When i test it on my live site (with a commercial theme) the qr code in .png format is displayed as a atring of characters similar to this.
�PNG IHDR{{n m<�PLTE���U��~ pHYs���+aIDATH���1�� ��P��H�W�]���� �΂0;>_�n�ζ�X����w����h�
The string is much longer, but i just put a snippet in to show what i mean.
Below is my plugin code and it includes the full untouched phpqrcode library.
<?php
/*
* Plugin Name: QR Code Generator
* Plugin URI: https://www.example.com/qr-code-generator
* Description: A plugin that allows you to easily generate QR codes for use on your website.
* Version: 1.0
* Author: Your Name
* Author URI: https://www.example.com
* License: GPL2
*/
include_once( plugin_dir_path( __FILE__ ) . 'phpqrcode/qrlib.php' );
function qr_code_shortcode( $atts ) {
// Extract the attributes
extract( shortcode_atts( array(
'text' => '',
), $atts ) );
global $post;
// Check if the shortcode is present in the post or page
if ( has_shortcode( $post->post_content, 'qr_code' ) ) {
// Check if the form has been submitted
if ( isset( $_POST['qr_code_text'] ) ) {
$text = sanitize_text_field( $_POST['qr_code_text'] );
// Generate the QR code
QRcode::png( $text );
} else {
// Display the form
ob_start();
echo '<form method="post">';
echo '<label for="qr_code_text">Enter the text for the QR code:</label><br>';
echo '<input type="text" name="qr_code_text" id="qr_code_text"><br>';
echo '<input type="submit" value="Generate QR Code">';
echo '</form>';
return ob_get_clean();
}
}
}
add_shortcode( 'qr_code', 'qr_code_shortcode' );
Any suggestions as to why it would work in one site and not on another ?
I've tried using base64 on the image thinking it was that but to no avail.

Related

Customizing the Parents functions.php File in Child

I'm customizing my theme right now. The Standard is, that the logged-in Users Avatar is shown in the Menu bar but I want to display a simple Icon there. I already wright the Code and everything works fine but the Code is located in the mains functions.php File. So in order to make the Site upgradeable, I need to embed the code in the child themes function.php. I found no help there so maybe here is someone who could help me!
Thanks a lot
Below is the Code which I need to embed in the functions.php File of my Child Theme:
add_action( 'init', 'gt3_get_page_id_from_menu' );
function gt3_user_avatar_out($avatar_size=80,$show_email=false){
$user_id = get_current_user_id();
$current_user = get_user_by( 'id', $user_id );
echo "<i class='gt3_login_icon gt3_login_icon--avatar'>";
echo '<i class="fa fa-user"></i>';
echo "</i>";
if ($show_email) {
echo "<span class='gt3_login__user_email'>".esc_html( $current_user->user_email )."</span>";
}
}
If a function is declared in the parent's functions.php, declaring a function with the same name in the child theme will cause a fatal error in the child theme itself. I'd suggest doing something like this instead:
parent function .php
// This can become a filter if you'll need to manipulate the current user
function gt3_get_current_user() {
return get_user_by( 'id', get_current_user_id() );
}
add_filter( 'gt3/current_user_avatar', function( string $html = '', bool $show_email = false ) {
$html .= '<i class="gt3_login_icon gt3_login_icon--avatar"><i class="fa fa-user"></i></i>';
if( $show_email ) {
$html .= sprintf( '<span class="gt3_login__user_email">%s</span>', esc_html( gt3_get_current_user()->user_email ) );
}
return $html;
}, 10, 2 );
child theme's function .php
add_filter( 'gt3/current_user_avatar', function( string $html = '', bool $show_email = false ) {
// $html here is the one that returned from the parent's theme. You can manipulate it or replace the whole output inside here.
return $html;
}, 10, 2 );
Example usages:
echo apply_filters( 'gt3/current_user_avatar', '', false ); // This will echo the icon without the email
echo apply_filters( 'gt3/current_user_avatar', '', true ); // This will echo the icon with the email
echo apply_filters( 'gt3/current_user_avatar', '<p>Append</p>', false ); // This will echo the icon without the email and the '<p>Append</p>' html string before everything else
The result will vary depending on where you use this filter. If you are in the child theme and you altered the html adding the said filter, the result will be customized for that theme. Remember that you can use the use statement to bring in external variables ina closure. For example:
$user_name = 'Mike';
add_filter( 'gt3/current_user_avatar', function( string $html = '', bool $show_email = false ) use ( $user_name ) {
$html .= sprintf( '<p>Hello, %s!</p>', $user_name );
return $html;
}, 10, 2 );
// This will cheer the user, and it will be place at the end of the snippet.
your code is not overwritten by adding a new functions.php file in the same folder, but do not copy/paste the code from the parent theme’s file, because it needs to remain separate from any modifications you make to the child theme. Instead, create a blank file or add any new .php functions required for your child theme

Parse XML into Wordpress WYSIWYG editor ONLY for Posts

I've run into a little situation that is hopefully possible to solve. My goal is to take an existing XML file from the server, parse it, and then inject it as a list into Wordpress's original WYSIWYG editor so that the site owner has the list readily available when he writes a new post. Right now, I have this code in my wp-admin/edit-form-advanced.php file:
/**
* Fires after the title field.
*
* #since 3.5.0
*
* #param WP_Post $post Post object.
*/
do_action( 'edit_form_after_title', $post );
if ( post_type_supports($post_type, 'editor') ) {
?>
<div id="postdivrich" class="postarea<?php if ( $_wp_editor_expand ) { echo ' wp-editor-expand'; } ?>">
<?php
/** LOAD XML FROM SERVER AND PARSE AS UL INTO EACH NEW WP POST **/
$xml = simplexml_load_file('../my-folder/file.xml');
$product = "<br/><br/><h2 style='text-align:center; color:#003300;'><u>Products Available Now</u></h2><br/><ul style='text-align:center; list-style:none; color:#003300;'>";
foreach( $xml as $value ) {
$product .= "<li>";
$product .= $value->Description .= " $";
$product .= $value->Price .= " / ";
$product .= $value->QtyUnit .= "\n";
$product .= "</li>";
};
?>
<?php wp_editor($product, 'content', array(
'_content_editor_dfw' => $_content_editor_dfw,
'drag_drop_upload' => true,
'tabfocus_elements' => 'content-html,save-post',
'editor_height' => 300,
'tinymce' => array(
'resize' => false,
'wp_autoresize_on' => $_wp_editor_expand,
'add_unload_trigger' => false,
),
) ); ?>
Although it works, this causes a couple issues.
1) It injects the data into every WYSIWYG editor, including pages, which I would like to avoid. The content should only appear in post editors if possible.
2) It causes a pretty serious bug that erases anything but the list whenever that particular admin page is reloaded. I can't save any drafts, or edit posts or pages unless I keep that session open in the browser during the editing process.
Not sure if these issues can be solved, but any and all help is sincerely appreciated!!
You should never modify WP core files. It's advisable that you update or restore the original files.
What you need can be achieved with this little plugin:
<?php
/**
* Plugin Name: Default Post Content
*/
add_action( 'load-post-new.php', 'new_post_so_44123076' );
function new_post_so_44123076() {
# Only load if post type not defined (only occurs for Posts)
if( isset($_GET['post_type']) )
return;
add_filter( 'default_content', 'default_content_so_44123076' );
}
function default_content_so_44123076( $content ) {
# Build your own custom content
$content = "My html content.";
return $content;
}
Make a folder for the plugin, put the code inside a file (custom-content.php) and put the XML on the same folder.
It can be retrieved like this:
$xml = plugins_url( '/file.xml', __FILE__ );

Developing Wordpress-Plugin: Problems with loading .js into head and HTML-Snippet as a Shortcode

I was asked to develope a Wordpress plugin for a project I am currently involved in, since I normally do Graphics and UX Design (CSS3). I am not that familiar with developing plugins for WP, although I've got quite some understanding of PHP. I've got the following code:
<?php
/**
* Plugin Name: ExpButton Wordpress Plugin
* Plugin URI: https://url.de
* Description: Ein Generator des Expbuttons
* Version: 0.1
* Author: Wilko Meyer
* Author URI: http://url.com
**/
/**
* Loading js into header
**/
function add_async($url)
{
if (strpos($url, '#asyncload')===false)
return $url;
else if (is_admin())
return str_replace('#asyncload', '', $url);
else
return str_replace('#asyncload', '', $url)."' async='async";
}
add_filter('clean_url', 'add_async', 11, 1);
function expertbuttonjs()
{
// Loading the JS
wp_register_script( 'custom-script', plugins_url( 'https://www.expert-button.de/js.js#asyncload', __FILE__ ), array( 'jquery', 'jquery-ui-core' ), '20120208', true );
wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'wptuts_scripts_with_the_lot' );
/**
*Creating Shortcode
**/
add_shortcode( 'shortcode', 'expbutton' );
function expbutton( $atts ) {
/* Turn on buffering */
ob_start(); ?>
<div style="overflow:hidden;font-size:9px;height:auto;width:auto;text-align:center;margin:auto;" id="expertbuttonbg"><a target="_bl$
<?php
/* Get the buffered content into a var */
$sc = ob_get_contents();
/**
*Expbutton to Shortcode
**/
add_shortcode( 'shortcode', 'expertbutton' );
function expertbutton( $atts ) {
ob_start(); ?>
<div style="overflow:hidden;font-size:9px;height:auto;width:auto;text-align:center;margin:auto;" id="expertbuttonbg"><a target="_bl$
<?php
$sc = ob_get_contents();
ob_end_clean();
/* Return the content as usual */
return $sc;
}
?>
The purpose of this plugin is to load the js.js as async into the of the page and to create an shortcode from the HTML Code below the /* Turn on buffering */ section which can be used at wordpress sites.
Currently the code does not load the js into header and the shortcode which should be created does not work either and I have no Idea why. Hope someone can help me with this problem & has some clue.
Why the plugin doesn't work?
Thanks in advance.
I have made some important littles changes. The html code of your buttons is incomplete (so I have try to guess). The name ou your javascript file seems to me very strange and unusual...
<?php
/**
* Plugin Name: ExpButton Wordpress Plugin
* Plugin URI: https://url.de
* Description: Ein Generator des Expbuttons
* Version: 0.1
* Author: Wilko Meyer
* Author URI: http://url.com
**/
/**
* Loading js into header
**/
function add_async($url)
{
if ( strpos($url, '#asyncload') === false )
return $url;
else if ( is_admin() )
return str_replace('#asyncload', '', $url);
else
return str_replace('#asyncload', '', $url)."' async='async";
}
add_filter('clean_url', 'add_async', 11, 1);
There was a problem in the url in wp_register_script() function that I have corrected and in the add_action() too: your javascript file has to be inside your plugin root folder (I mean not in a subfolder). Also your JS file name seems to me very strange (normally it's file finishing with .js extension and not with .js#asyncload):
function expertbuttonjs()
{
// Loading the JS
wp_register_script( 'custom-script', plugins_url('/js.js#asyncload', __FILE__ ), array( 'jquery', 'jquery-ui-core' ), '20120208', true );
wp_enqueue_script( 'custom-script' );
}
add_action( 'wp_enqueue_scripts', 'expertbuttonjs' );
Dont use shortcode name for shortcodes functions. The code of your buttons are incomplete in your code. Also you can't have 2 times the same name for shortcodes or functions:
/*
* expbutton Shortcodes
*/
add_shortcode( 'expbutton', 'expbutton' );
function expbutton( $atts ) {
/* Turn on buffering */
ob_start(); ?>
<div style="overflow:hidden;font-size:9px;height:auto;width:auto;text-align:center;margin:auto;" id="expertbuttonbg"><a target="_blank" href="'.$sc.'">Text Button</a><div>
<?php
/* Get the buffered content into a var */
$sc = ob_get_contents();
/*
* expertbutton Shortcode
*/
add_shortcode( 'expertbutton', 'expertbutton' );
function expertbutton( $atts ) {
ob_start(); ?>
<div style="overflow:hidden;font-size:9px;height:auto;width:auto;text-align:center;margin:auto;" id="expertbuttonbg"><a target="_blank" href="'.$sc.'">Text Button</a><div>
<?php
$sc = ob_get_contents();
ob_end_clean();
/* Return the content as usual */
return $sc;
}
?>
This should work now.

New text area not storing data on save in WP Settings General

I am trying to create a text area in WordPress general settings, which allows a disclaimer or other info to show at the bottom of each page of the website template.
It works fine using the input tag, however when I change to textarea it will not store the data on save.
I have been searching online, but haven't found the right solution.
Here is the current code I am using:
<?php
$new_general_setting_disclaimer = new new_general_setting_disclaimer();
class new_general_setting_disclaimer {
function new_general_setting_disclaimer( ) {
add_filter( 'admin_init' , array( &$this , 'register_fields' ) );
}
function register_fields() {
register_setting( 'general', 'disclaimer', 'esc_attr' );
add_settings_field('disclaimer', '<label for="disclaimer">'.__('Website Disclaimer' , 'disclaimer' ).'</label>' , array(&$this, 'fields_html') , 'general' );
}
function fields_html() {
$value = get_option( 'disclaimer' );
echo '<textarea id="disclaimer" name="disclaimer" cols="50" rows="5" value="'. $value .'" /></textarea>';
}
}
?>
Thanks in advance. Please let me know if you need more info.

Targeting a specific `<div>` via Wordpress Plugin

Insert HTML Input to a themes template file?
My question is this:
Currently with my code, I can have whatever I've set in my custom settings page appear on
the end of every post using, of course, a WordPress filter.
The only thing is, I don't want what I input to go anywhere within a post. What I am trying to
achieve, is to have my input injected into the current themes home.php template file, within a <div></div> tag that's contained within that template file. The <div> in question has an ID attached, which is <div id="category-inner">, so is there any way use it's ID to target it in my plugin?
I've successfully managed to do it, by editing the actual home.php template file and inserting a bit of php directly there to show the user input, but that totally goes against what I'm trying to do, which is to not have to edit the source code of the template file and only have to use my plugin to insert the users inputted text in that specific location (the <div> mentioned above).
My plugin is only ever going to be adding user input in one place on the site, and it will never change. And the place it will always go in, is where I mentioned above.
Below is my plugin code:
<?php
/*/
Plugin Name: Custom Text Adder
Plugin URI: N/A
Description: Demonstrates how rubbish I am at pretty much everything I want to do
Version: 101
Author: JD
Author URI: N/A
/*/
// insert custom plugin settings menu
add_action('admin_menu', 'custom_create_menu');
add_filter('the_content', 'customhead_the_content');
function customhead_the_content($content) {
$output = $content;
$output .= '<div id="category-inner">';
$output .= get_option('post_text');
$output .= '</div>';
return $output;
}
// Add Font-Size to WYSIWYG Editor
function wp_editor_fontsize_filter( $options ) {
array_shift( $options );
array_unshift( $options, 'fontsizeselect');
array_unshift( $options, 'formatselect');
return $options;
}
add_filter('mce_buttons_2', 'wp_editor_fontsize_filter');
// Create Custom Menu
function custom_create_menu() {
//create new top-level menu
add_menu_page('Custom Plugin Settings', 'Custom Settings', 'administrator', __FILE__, 'custom_settings_page',plugins_url('/img/icon.png', __FILE__));
//call register settings function
add_action( 'admin_init', 'register_mysettings' );
}
// Register our settings
function register_mysettings() {
register_setting( 'custom-settings-group', 'new_option_name' );
register_setting( 'custom-settings-group', 'some_other_option' );
register_setting( 'custom-settings-group', 'option_etc' );
register_setting( 'custom-settings-group', 'font_size' );
register_setting( 'custom-settings-group', 'post_text' );
}
function custom_settings_page() {
?>
<!-- Custom Settings Page Container -->
<div class="wrap">
<h2>Custom Text</h2>
<form method="post" action="options.php">
<?php settings_fields( 'custom-settings-group' ); ?>
<table class="form-table">
<?php /* Bring the editor onto the page */
wp_editor( '', 'post_text', $settings = array() );
// 4.
// Custom buttons for the editor.
// This is a list separated with a comma after each feature
// eg. link, unlink, bold, ...
$settings = array(
'textarea_name' => 'post_text',
'media_buttons' => true,
'tinymce' => array(
'theme_advanced_buttons1' => 'formatselect,|,bold,italic,underline,|,' .
'bullist,blockquote,|,justifyleft,justifycenter' .
',justifyright,justifyfull,|,link,unlink,|' .
',spellchecker,wp_fullscreen,wp_adv'
)
);
submit_button( 'Save everything', 'primary', 'submit' ); ?>
</table>
</form>
</div>
<?php }; ?>
Here is the screenshot which will be able to explain this in the most concise way possible:
http://i.imgur.com/hiEjEsA.jpg
Again, any and all help is hugely appreciated and will hopefully stop my brain from hurting!
You all rock,
Casey. :)
I'm not sure if you want this to be a pure PHP solution, but since you have the ID of the div you could target it with jQuery and insert the text into the div on page load (or form submit) with something like this:
$(document).ready(function() {
var userText = $('#input-id').val();
$('#category-inner').html(userText);
})

Categories