twitter oAuth for developers wordpress - can't output tweets - php

I am using a great script called twitter oAuth for developers to create a twitter feed plugin for my wordpress site. The aim is to create a widget where the user can enter their username and number of tweets to display, and that shows in the clients site.
Twitter oAuth for developers creates the following function that is used to display tweets:
getTweets($number_of_tweets, $twitter_screenname_to_load);
Since I am allowing the user to change the username and no. of tweets, I have changed it to this:
$no_of_tweets = $widget['no_of_tweets'];
$twitter_username = $widget['twitter_username'];
$tweets = getTweets($no_of_tweets, ''.$twitter_username.'');
Where $widget['no_of_tweets'] and $widget['twitter_username'] are parameters specified by the user.
I have set defaults for this plugin as follows:
/* Setup Widget Defaults */
$this->defaults = array (
...
'twitter_username' => 'skizzar_sites',
'no_of_tweets' => 3,
...
)
);
So when I load up my plugin, it shows the latest 3 tweets from skizzar_sites - as it should. However, when the user change the number or username, the widget outputs a single random tweet from a random user.
Is there something obviously wrong with the way I have written the function:
$tweets = getTweets($no_of_tweets, ''.$twitter_username.'');
Here is my full widget code for reference:
<?php /**
* Layers Twitter Widget
*
* This file is used to register and display the Layers widget.
* http://docs.layerswp.com/development-tutorials-layers-builder-widgets/
*
* #package Layers
* #since Layers 1.0.0
*/
if( !class_exists( 'Layers_Twitter_Widget' ) && class_exists( 'Layers_Widget' ) ) {
// http://docs.layerswp.com/development-tutorials-layers-builder-widgets/#widget-class
class Layers_Twitter_Widget extends Layers_Widget {
/**
* 1 - Widget construction
* http://docs.layerswp.com/development-tutorials-layers-builder-widgets/#1-widget-construction
*/
function Layers_Twitter_Widget(){
$this->widget_title = __( 'Tweets' , 'layerswp' );
$this->widget_id = 'tweets';
$this->post_type = '';
$this->taxonomy = '';
$this->checkboxes = array();
/* Widget settings. */
$widget_ops = array(
'classname' => 'obox-layers-' . $this->widget_id .'-widget',
'description' => __( 'This widget is used to display your Tweets', 'layerswp')
);
/* Widget control settings. */
$control_ops = array(
'width' => '660',
'height' => NULL,
'id_base' => 'layers-widget-' . $this->widget_id
);
/* Create the widget. */
parent::__construct( 'layers' . '-widget-' . $this->widget_id , $this->widget_title, $widget_ops, $control_ops );
/* Setup Widget Defaults */
$this->defaults = array (
'title' => __( 'Twitter Feed', 'layerswp' ),
'excerpt' => __( 'Display a list of your most recent tweets', 'layerswp' ),
'twitter_username' => 'skizzar_sites',
'no_of_tweets' => 3,
'design' => array(
'layout' => 'layout-boxed',
'textalign' => 'text-left',
'background' => array(
'position' => 'center',
'repeat' => 'no-repeat'
),
'fonts' => array(
'align' => 'text-left',
'size' => 'medium',
'color' => NULL,
'shadow' => NULL
)
)
);
} // END main function
/**
* 2 - Widget form
* http://docs.layerswp.com/development-tutorials-layers-builder-widgets/#2-widget-form
* We use regulage HTML here, it makes reading the widget much easier
* than if we used just php to echo all the HTML out.
*
*/
function form( $instance ){
// $instance Defaults
$instance_defaults = $this->defaults;
// If we have information in this widget, then ignore the defaults
if( !empty( $instance ) ) $instance_defaults = array();
// Parse $instance
$instance = wp_parse_args( $instance, $instance_defaults );
extract( $instance, EXTR_SKIP );
// Design Bar Components
$design_bar_components = apply_filters(
'layers_' . $this->widget_id . '_widget_design_bar_components' ,
array(
'layout',
'fonts',
'background',
'advanced'
)
);
// Instantiate the Deisgn Bar
$this->design_bar(
'side', // CSS Class Name
array(
'name' => $this->get_field_name( 'design' ),
'id' => $this->get_field_id( 'design' ),
), // Widget Object
$instance, // Widget Values
$design_bar_components // Standard Components
);
// Build Content Form
// http://docs.layerswp.com/development-tutorials-layers-builder-widgets/#content-options-form
?>
<div class="layers-container-large">
<?php
$this->form_elements()->header(
array(
'title' => __( 'Tweets' , 'layerswp' ),
'icon_class' => 'post'
)
);
?>
<section class="layers-accordion-section layers-content">
<div class="layers-row layers-push-bottom">
<p>In order for the twitter widget to work, you will need to set up a twitter app and add your API credentials to the dashboard. Click here to enter your API details.</p>
<p class="layers-form-item">
<?php echo $this->form_elements()->input(
array(
'type' => 'text',
'name' => $this->get_field_name( 'title' ) ,
'id' => $this->get_field_id( 'title' ) ,
'placeholder' => __( 'Enter title here' , 'layerswp' ),
'value' => ( isset( $title ) ) ? $title : NULL ,
'class' => 'layers-text layers-large'
)
); ?>
</p>
<p class="layers-form-item">
<?php echo $this->form_elements()->input(
array(
'type' => 'rte',
'name' => $this->get_field_name( 'excerpt' ) ,
'id' => $this->get_field_id( 'excerpt' ) ,
'placeholder' => __( 'Short Excerpt' , 'layerswp' ),
'value' => ( isset( $excerpt ) ) ? $excerpt : NULL ,
'class' => 'layers-textarea layers-large'
)
); ?>
</p>
<p class="layers-form-item">
<?php
echo $this->form_elements()->input(
array(
'type' => 'text',
'name' => $this->get_field_name( 'twitter_username' ) ,
'id' => $this->get_field_id( 'twitter_username' ) ,
'placeholder' => __( 'Twitter username' , 'layerswp' ),
'value' => ( isset( $twitter_username ) ) ? $twitter_username : NULL ,
'class' => 'layers-text layers-large'
)
); ?>
</p>
<p class="layers-form-item">
<?php
echo __( 'Number of tweets to show' , 'layerswp' );
echo $this->form_elements()->input(
array(
'type' => 'number',
'name' => $this->get_field_name( 'no_of_tweets' ) ,
'id' => $this->get_field_id( 'no_of_tweets' ) ,
'value' => ( isset( $no_of_tweets ) ) ? $no_of_tweets : NULL ,
'min' => '1',
'max' => '20'
)
); ?>
</p>
</div>
</section>
</div>
<?php
} // Form
/**
* 3 - Update Options
* http://docs.layerswp.com/development-tutorials-layers-builder-widgets/#3-update-controls
*/
function update($new_instance, $old_instance) {
if ( isset( $this->checkboxes ) ) {
foreach( $this->checkboxes as $cb ) {
if( isset( $old_instance[ $cb ] ) ) {
$old_instance[ $cb ] = strip_tags( $new_instance[ $cb ] );
}
} // foreach checkboxes
} // if checkboxes
return $new_instance;
}
/**
* 4 - Widget front end display
* http://docs.layerswp.com/development-tutorials-layers-builder-widgets/#4-widget-front-end
*/
function widget( $args, $instance ) {
// Turn $args array into variables.
extract( $args );
// $instance Defaults
$instance_defaults = $this->defaults;
// If we have information in this widget, then ignore the defaults
if( !empty( $instance ) ) $instance_defaults = array();
// Parse $instance
$widget = wp_parse_args( $instance, $instance_defaults );
// Apply Styling
// http://docs.layerswp.com/development-tutorials-layers-builder-widgets/#colors-and-font-settings
layers_inline_styles( '#' . $widget_id, 'background', array( 'background' => $widget['design'][ 'background' ] ) );
layers_inline_styles( '#' . $widget_id, 'color', array( 'selectors' => array( '.section-title h3.heading' , '.section-title div.excerpt' ) , 'color' => $widget['design']['fonts'][ 'color' ] ) );
// Apply the advanced widget styling
$this->apply_widget_advanced_styling( $widget_id, $widget );
// Generate the widget container class
// Do not edit
$widget_container_class = array();
$widget_container_class[] = 'widget row content-vertical-massive';
$widget_container_class[] = $this->check_and_return( $widget , 'design', 'advanced', 'customclass' );
$widget_container_class[] = $this->get_widget_spacing_class( $widget );
$widget_container_class = implode( ' ', apply_filters( 'layers_post_widget_container_class' , $widget_container_class ) );
/**
* Widget Markup
* http://docs.layerswp.com/development-tutorials-layers-builder-widgets/#widget-html
*/
?>
<section class=" <?php echo $widget_container_class; ?>" id="<?php echo $widget_id; ?>">
<?php if( '' != $this->check_and_return( $widget , 'title' ) ||'' != $this->check_and_return( $widget , 'excerpt' ) ) { ?>
<div class="container clearfix">
<?php
// Generate the Section Title Classes
$section_title_class = array();
$section_title_class[] = 'section-title clearfix';
$section_title_class[] = $this->check_and_return( $widget , 'design', 'fonts', 'size' );
$section_title_class[] = $this->check_and_return( $widget , 'design', 'fonts', 'align' );
$section_title_class[] = ( $this->check_and_return( $widget, 'design', 'background' , 'color' ) && 'dark' == layers_is_light_or_dark( $this->check_and_return( $widget, 'design', 'background' , 'color' ) ) ? 'invert' : '' );
$section_title_class = implode( ' ', $section_title_class ); ?>
<div class="<?php echo $section_title_class; ?>">
<?php if( '' != $widget['title'] ) { ?>
<h3 class="heading"><?php echo esc_html( $widget['title'] ); ?></h3>
<?php } ?>
<?php if( '' != $widget['excerpt'] ) { ?>
<div class="excerpt"><?php echo $widget['excerpt']; ?></div>
<?php } ?>
</div>
</div>
<?php }
// Begin Post Structure ?>
<div class="row <?php echo $this->get_widget_layout_class( $widget ); ?> <?php echo $this->check_and_return( $widget , 'design', 'liststyle' ); ?>">
<?php //start Twitter output
// draft sample display for array returned from oAuth Twitter Feed for Developers WP plugin
// http://wordpress.org/extend/plugins/oauth-twitter-feed-for-developers/
$no_of_tweets = $widget['no_of_tweets'];
$twitter_username = $widget['twitter_username'];
$tweets = getTweets($no_of_tweets, ''.$twitter_username.'');
if(is_array($tweets)){
// to use with intents
echo '<script type="text/javascript" src="//platform.twitter.com/widgets.js"></script>';
foreach($tweets as $tweet){
if($tweet['text']){
$the_tweet = $tweet['text'];
// i. User_mentions must link to the mentioned user's profile.
if(is_array($tweet['entities']['user_mentions'])){
foreach($tweet['entities']['user_mentions'] as $key => $user_mention){
$the_tweet = preg_replace(
'/#'.$user_mention['screen_name'].'/i',
'#'.$user_mention['screen_name'].'',
$the_tweet);
}
}
// ii. Hashtags must link to a twitter.com search with the hashtag as the query.
if(is_array($tweet['entities']['hashtags'])){
foreach($tweet['entities']['hashtags'] as $key => $hashtag){
$the_tweet = preg_replace(
'/#'.$hashtag['text'].'/i',
'#'.$hashtag['text'].'',
$the_tweet);
}
}
// iii. Links in Tweet text must be displayed using the display_url
// field in the URL entities API response, and link to the original t.co url field.
if(is_array($tweet['entities']['urls'])){
foreach($tweet['entities']['urls'] as $key => $link){
$the_tweet = preg_replace(
'`'.$link['url'].'`',
''.$link['url'].'',
$the_tweet);
}
}
echo $the_tweet;
// 3. Tweet Actions
// Reply, Retweet, and Favorite action icons must always be visible for the user to interact with the Tweet. These actions must be implemented using Web Intents or with the authenticated Twitter API.
// No other social or 3rd party actions similar to Follow, Reply, Retweet and Favorite may be attached to a Tweet.
// get the sprite or images from twitter's developers resource and update your stylesheet
echo '
<ul class="twitter_intents">
<li><a class="reply" href="https://twitter.com/intent/tweet?in_reply_to='.$tweet['id_str'].'"><i class="fa fa-reply"></i>R</a></li>
<li><a class="retweet" href="https://twitter.com/intent/retweet?tweet_id='.$tweet['id_str'].'"><i class="fa fa-retweet"></i>R</a></li>
<li><a class="favorite" href="https://twitter.com/intent/favorite?tweet_id='.$tweet['id_str'].'"><i class="fa fa-heart"></i>F</a></li>
</ul>';
// 4. Tweet Timestamp
// The Tweet timestamp must always be visible and include the time and date. e.g., “3:00 PM - 31 May 12”.
// 5. Tweet Permalink
// The Tweet timestamp must always be linked to the Tweet permalink.
echo '
<p class="timestamp">
<a href="https://twitter.com/YOURUSERNAME/status/'.$tweet['id_str'].'" target="_blank">
'.date('h:i A M d',strtotime($tweet['created_at']. '- 8 hours')).'
</a>
</p>';// -8 GMT for Pacific Standard Time
} else {
echo '
<br /><br />
Click here to read YOURUSERNAME\'S Twitter feed';
}
}
}
// end Twitter output ?>
</div>
</section>
<?php }
} // Class
// Register our widget
// http://docs.layerswp.com/development-tutorials-layers-builder-widgets/#register-and-initialize
register_widget('Layers_Twitter_Widget');
}

Aha! Just figured this out - remembered from a few years back having a similar problem and it was because the no_of_tweets and _username paramteres in the function are documented the wrong way round.
Instead of
getTweets($number_of_tweets, $twitter_screenname_to_load);
its:
getTweets($twitter_screenname_to_load, $number_of_tweets);

Related

Filter comments with meta key in wordpress using wp_list_comments()

Basically I am trying to do filter the comments with 'meta_key' and value. I have get the comment meta data but reply link is not appear. Anyone help me out from this. I tried with wp_list_comments() but that I don't know how to use meta_key value.
Here is code:
<div class="comment-section">
<?php
$issue = array(
'meta_query' => array(
array(
'key' => 'comment-type',
'value' => 'Idea'
)
)
);
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $issue );
if( $comments ) :
foreach( $comments as $comment ) :
?>
<div class="comment-author vcard">
<?php echo($comment->comment_content);?>
<div class="reply"><?php
// Display comment reply link
comment_reply_link( array_merge( $args, array(
'add_below' => $add_below,
'depth' => $depth,
'max_depth' => $args['max_depth']
) ) ); ?>
</div>
</div><!-- .comment-details -->
<?php
endforeach;
endif;
?>
</div>
Please let me know how to appear the reply link.
I've solved it
$comments = get_comments(array(
'post_id' => $post->ID,
'status' => 'approve',
'type' => 'comment',
'meta_key' => 'comment-type',
'meta_value' => 'Issue',
));
if($comments)
{
wp_list_comments(array(
'per_page' => 10, // Allow comment pagination
), $comments);
}
else
{
comment_form();
}
u can try with this function i guess
function wp_filter_comment( $commentdata ) {
if ( isset( $commentdata['user_ID'] ) ) {
/**
* Filters the comment author's user ID before it is set.
*
* The first time this filter is evaluated, 'user_ID' is checked
* (for back-compat), followed by the standard 'user_id' value.
*
* #since 1.5.0
*
* #param int $user_ID The comment author's user ID.
*/
$commentdata['user_id'] = apply_filters( 'pre_user_id', $commentdata['user_ID'] );
} elseif ( isset( $commentdata['user_id'] ) ) {
/** This filter is documented in wp-includes/comment.php */
$commentdata['user_id'] = apply_filters( 'pre_user_id', $commentdata['user_id'] );
}
return $commentdata;
}

Woocommerce Custom Payment Gateway Not Redirecting

I have a WC payment gateway which was build and working until WP version 4.1. Today I started testing it on WP 4.9.8 and WC 3.5.1.
When I try to complete purchase the payment gateway is not taking me to the payment screen to fill credit card details. It get stuck on redirection state.
Hope someone can help me out to solve this.
Below the image reference and the code I am using:
<?php
/**
* Plugin Name: CustomPaymentGateway
*/
add_action('plugins_loaded', 'init_mpay', 0);
function init_mpay() {
if ( ! class_exists( 'WC_Payment_Gateway' ) ) return;
class woocommerce_mpay extends WC_Payment_Gateway {
public function __construct() {
global $woocommerce;
$this->id = 'mpay';
$this->method_title = __('MPay', 'mpay-chearaan-woo');
$this->icon = plugins_url( 'mpay.png', __FILE__ );
$this->has_fields = false;
$this->notify_url = str_replace( 'https:', 'http:', add_query_arg( 'wc-api', 'woocommerce_mpay', home_url( '/' ) ) );
// Load the form fields.
$this->init_form_fields();
// Load the settings.
$this->init_settings();
// Define user set variables
$this->mpayurl = $this->settings['mpayurl'];
$this->title = $this->settings['title'];
$this->description = $this->settings['description'];
$this->merchantid = $this->settings['merchantid'];
$this->hashKey = $this->settings['hashKey'];
$this->transactionDate = date('Y-m-d H:i:s O');
$this->woo_version = $this->get_woo_version();
// Actions
add_action('init', array(&$this, 'successful_request'));
add_action('woocommerce_api_woocommerce_mpay', array( &$this, 'successful_request' ));
add_action('woocommerce_receipt_mpay', array(&$this, 'receipt_page'));
if ( version_compare( WOOCOMMERCE_VERSION, '2.0.0', '>=' ) ) {
add_action('woocommerce_update_options_payment_gateways_' . $this->id, array( &$this, 'process_admin_options' ));
} else {
add_action('woocommerce_update_options_payment_gateways', array( &$this, 'process_admin_options' ));
}
}
/**
* Initialise Gateway Settings Form Fields
*/
function init_form_fields() {
$this->form_fields = array(
'enabled' => array(
'title' => __( 'Enable/Disable:', 'mpay-chearaan-woo' ),
'type' => 'checkbox',
'label' => __( 'Enable MPay', 'mpay-chearaan-woo' ),
'default' => 'yes'
),
'mpayurl' => array(
'title' => __( 'UAT/Production:', 'mpay-chearaan-woo' ),
'type' => 'checkbox',
'label' => __( 'UAT', 'mpay-chearaan-woo' ),
'default' => 'yes'
),
'title' => array(
'title' => __( 'Title:', 'mpay-chearaan-woo' ),
'type' => 'text',
'description' => __( 'The title which the user sees during checkout.', 'mpay-chearaan-woo' ),
'default' => __( 'MPay Online Payment Gateway', 'mpay-chearaan-woo' )
),
'description' => array(
'title' => __( 'Description:', 'mpay-chearaan-woo' ),
'type' => 'textarea',
'description' => __( 'Description which the user sees during checkout.', 'mpay-chearaan-woo' ),
'default' => __('Pay securely through MPay\'s Secure Servers.', 'mpay-chearaan-woo')
),
'merchantid' => array(
'title' => __( 'Merchant ID:', 'mpay-chearaan-woo' ),
'type' => 'text',
'description' => __( 'Please enter your Merchant ID as provided by MPay.', 'mpay-chearaan-woo' ),
'default' => ''
),
'hashKey' => array(
'title' => __( 'Merchant hashKey:', 'mpay-chearaan-woo' ),
'type' => 'text',
'description' => __( 'Please enter your Merchant hashKey as provided by MPay.', 'mpay-chearaan-woo' ),
'default' => ''
)
);
}
public function admin_options() {
?>
<h3>MPay</h3>
<p><?php _e('MPay works by sending the user to MPay to enter their payment information.', 'mpay-chearaan-woo'); ?></p>
<table class="form-table">
<?php
// Generate the HTML For the settings form.
$this->generate_settings_html();
?>
</table><!--/.form-table-->
<?php
} // End admin_options()
/**
* There are no payment fields, but we want to show the description if set.
**/
function payment_fields() {
if ($this->description) echo wpautop(wptexturize($this->description));
}
/**
* Generate the button link
**/
public function generate_mpay_form( $order_id ) {
global $woocommerce;
$order = new WC_Order( $order_id );
if ($this->mpayurl == "yes"){
$mpay_adr = "https://pcimdex.mpay.my/mdex2/payment/eCommerce";
}else{
$mpay_adr = "https://www.mdex.my/mdex/payment/eCommerce";
}
$sHash = strtoupper(hash('sha256', $this->hashKey."Continue".str_pad($this->merchantid, 10, '0', STR_PAD_LEFT).str_pad($order->id, 20, '0', STR_PAD_LEFT).str_pad(($order->order_total*100), 12, '0', STR_PAD_LEFT)));
$mpay_args = array(
'secureHash' => $sHash,
'mid' => str_pad($this->merchantid, 10, '0', STR_PAD_LEFT),
'invno' => str_pad($order->id, 20, '0', STR_PAD_LEFT),
'amt' => str_pad(($order->order_total*100), 12, '0', STR_PAD_LEFT),
'desc' => str_pad("Order No ".$order_id, 255, ' ', STR_PAD_RIGHT),
'postURL' => $this->notify_url,
'phone' => $order->billing_phone,
'email' => $order->billing_email,
'param' => 'WC|V1'
);
$mpay_args_array = array();
foreach ($mpay_args as $key => $value) {
$mpay_args_array[] = '<input type="hidden" name="'.$key.'" value="'. $value .'" /><br>';
}
wc_enqueue_js('
jQuery(function(){
jQuery("body").block(
{
message: "<img src=\"'.$woocommerce->plugin_url().'/images/uploading.gif\" alt=\"Redirecting…\" style=\"float:left; margin-right: 10px;\" />'.__('Thank you for your order. We are now redirecting you to MPay to make payment.', 'mpay-chearaan-woo').'",
overlayCSS:
{
background: "#fff",
opacity: 0.5
},
css: {
padding: 18,
textAlign: "center",
color: "#555",
border: "2px solid #aaa",
backgroundColor:"#fff",
cursor: "wait",
lineHeight: "30px"
}
});
jQuery("#submit_mpay_payment_form").click();
});
');
return '<form action="'.$mpay_adr.'" method="post">
' . implode('', $mpay_args_array) . '
<input type="submit" class="button-alt" id="submit_mpay_payment_form" value="'.__('Pay via MPay', 'mpay-chearaan-woo').'" /> <a class="button cancel" href="'.$order->get_cancel_order_url().'">'.__('Cancel order & restore cart', 'mpay-chearaan-woo').'</a>
</form>';
}
/**
* Process the payment and return the result
**/
function process_payment( $order_id ) {
$order = new WC_Order( $order_id );
if($this->woo_version >= 2.1){
$redirect = $order->get_checkout_payment_url( true );
}else if( $this->woo_version < 2.1 ){
$redirect = add_query_arg('order', $order->id, add_query_arg('key', $order->order_key, get_permalink(get_option('woocommerce_pay_page_id'))));
}else{
$redirect = add_query_arg('order', $order->id, add_query_arg('key', $order->order_key, get_permalink(get_option('woocommerce_pay_page_id'))));
}
return array(
'result' => 'success',
'redirect' => $redirect
);
}
/**
* receipt_page
**/
function receipt_page( $order ) {
echo '<p>'.__('Please click the button below to pay with MPay.', 'mpay-chearaan-woo').'</p>';
echo $this->generate_mpay_form( $order );
}
/**
* Server callback was valid, process callback (update order as passed/failed etc).
**/
function successful_request($mpay_response) {
global $woocommerce;
if (isset($_GET['wc-api']) && $_GET['wc-api'] == 'woocommerce_mpay') {
/** need to trim from result **/
$Url_result = $_GET['result'];
$order = new WC_Order( (int) substr($Url_result,7,20) );
$tranID = (int)substr($Url_result,1,6);
if (substr($Url_result,0,1) == '0'){
$r_status = 0;
}else{
$r_status = 33;
}
/*
$order = new WC_Order( (int) $_POST['invno'] );
$r_status = (int) $_POST['result'];
*/
if ($r_status == '0' ){
$order->payment_complete();
$order->add_order_note('MPay Payment was SUCCESSFUL '.'<br>AuthCode is ' . $tranID);
wp_redirect( $this->get_return_url($order) ); exit;
//wp_redirect( $this->order->get_checkout_order_received_url() ); exit;
}else{
$order->update_status('failed', sprintf(__('MPay Payment Failed. Error Communicating with Bank.', 'mpay-chearaan-woo') ) );
wp_redirect($order->get_cancel_order_url()); exit;
}
}
}
function get_woo_version() {
// If get_plugins() isn't available, require it
if ( ! function_exists( 'get_plugins' ) )
require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
// Create the plugins folder and file variables
$plugin_folder = get_plugins( '/woocommerce' );
$plugin_file = 'woocommerce.php';
// If the plugin version number is set, return it
if ( isset( $plugin_folder[$plugin_file]['Version'] ) ) {
return $plugin_folder[$plugin_file]['Version'];
} else {
// Otherwise return null
return NULL;
}
}
}
}
/**
* Add the gateway to WooCommerce
**/
function add_mpay( $methods ) {
$methods[] = 'woocommerce_mpay'; return $methods;
}
add_filter('woocommerce_payment_gateways', 'add_mpay' );

editing wordpress custom header php file

I am using an open source theme for a wordpress website. While most of the site is done, I am having trouble adding a second slogan area to our site.
Additionally, I am attempting to modify customer_header.php to make the front page showcase appear on all pages as well.
Currently the home page is the only page displaying the header showcase and only has two lines of text. The following is the php:
<?php
/**
* Sample implementation of the Custom Header feature.
*
* #link http://codex.wordpress.org/Custom_Headers
*
* #package refur
*/
class refur_custom_header {
/**
* A reference to an instance of this class.
*
* #var object
*/
private static $instance = null;
/**
* Default header settings array
*
* #var array
*/
public $default_settings = array();
/**
* Holder for active showcase trigger
*
* #var bool
*/
public $is_showcase = null;
function __construct() {
add_filter( 'body_class', array( $this, 'add_body_classes' ) );
add_action( 'after_setup_theme', array( $this, 'custom_header_setup' ) );
add_action( 'refur_header_showcase', array( $this, 'public_callback' ) );
add_action( 'customize_register', array( $this, 'header_settings' ) );
$this->default_settings = array(
'header_mask_color' => '#000000',
'header_mask_fill' => 50,
'header_slogan_title' => __( 'Your Awesome Blog', 'refur' ),
'header_slogan_text' => __( 'Just a few words why you blog is so awesome', 'refur' ),
'header_button_text' => __( 'Call to action', 'refur' ),
'header_button_url' => '#'
);
}
/**
* Set up the WordPress core custom header feature.
*
* #uses refur_header_style()
* #uses refur_admin_header_style()
* #uses refur_admin_header_image()
*/
function custom_header_setup() {
add_theme_support( 'custom-header', apply_filters( 'refur_custom_header_args', array(
'default-image' => get_template_directory_uri() . '/images/header-image.png',
'default-text-color' => 'ffffff',
'width' => 2000,
'height' => 765,
'flex-height' => true,
'wp-head-callback' => array( $this, 'header_style' ),
'admin-head-callback' => array( $this, 'admin_header_style' ),
'admin-preview-callback' => array( $this, 'admin_header_image' ),
) ) );
}
/**
* Register additional setting for header section
*
* #param object $wp_customize customizer object
* #return void
*/
function header_settings( $wp_customize ) {
$wp_customize->add_setting('refur[header_mask_color]', array(
'default' => $this->default_settings['header_mask_color'],
'capability' => 'edit_theme_options',
'type' => 'theme_mod',
'sanitize_callback' => 'sanitize_hex_color',
));
$wp_customize->add_control( new WP_Customize_Color_Control( $wp_customize, 'refur_header_mask_color', array(
'label' => __( 'Image Mask Color', 'refur' ),
'section' => 'header_image',
'settings' => 'refur[header_mask_color]',
)));
$wp_customize->add_setting( 'refur[header_mask_fill]', array(
'default' => $this->default_settings['header_mask_fill'],
'type' => 'theme_mod',
'sanitize_callback' => 'refur_sanitize_num',
) );
$wp_customize->add_control( 'refur_header_mask_fill', array(
'label' => __( 'Image mask fill level', 'refur' ),
'section' => 'header_image',
'settings' => 'refur[header_mask_fill]',
'type' => 'number',
'input_attrs' => array(
'min' => 0,
'max' => 100,
'step' => 1,
),
) );
$wp_customize->add_setting( 'refur[header_slogan_title]', array(
'default' => $this->default_settings['header_slogan_title'],
'type' => 'theme_mod',
'sanitize_callback' => 'sanitize_text_field',
) );
$wp_customize->add_control( 'refur_header_slogan_title', array(
'label' => __( 'Header slogan title', 'refur' ),
'section' => 'header_image',
'settings' => 'refur[header_slogan_title]',
'type' => 'text',
) );
$wp_customize->add_setting( 'refur[header_slogan_text]', array(
'default' => $this->default_settings['header_slogan_text'],
'type' => 'theme_mod',
'sanitize_callback' => 'sanitize_text_field',
) );
$wp_customize->add_control( 'refur_header_slogan_text', array(
'label' => __( 'Header slogan description', 'refur' ),
'section' => 'header_image',
'settings' => 'refur[header_slogan_text]',
'type' => 'text',
) );
$wp_customize->add_setting( 'refur[header_button_text]', array(
'default' => $this->default_settings['header_button_text'],
'type' => 'theme_mod',
'sanitize_callback' => 'sanitize_text_field',
) );
$wp_customize->add_control( 'refur_header_button_text', array(
'label' => __( 'Header button text (leave empty to remove button)', 'refur' ),
'section' => 'header_image',
'settings' => 'refur[header_button_text]',
'type' => 'text',
) );
$wp_customize->add_setting( 'refur[header_button_url]', array(
'default' => $this->default_settings['header_button_url'],
'type' => 'theme_mod',
'sanitize_callback' => 'refur_sanitize_url',
) );
$wp_customize->add_control( 'refur_header_button_url', array(
'label' => __( 'Header button URL', 'refur' ),
'section' => 'header_image',
'settings' => 'refur[header_button_url]',
'type' => 'text',
) );
}
/**
* Custom header image markup displayed on the Appearance > Header admin panel.
*
* #see custom_header_setup().
*/
function admin_header_image() {
?>
<div id="headimg">
<h1 class="displaying-header-text">
<a id="name" style="<?php echo esc_attr( 'color: #' . get_header_textcolor() ); ?>" onclick="return false;" href="<?php echo esc_url( home_url( '/' ) ); ?>"><?php bloginfo( 'name' ); ?></a>
</h1>
<div class="displaying-header-text" id="desc" style="<?php echo esc_attr( 'color: #' . get_header_textcolor() ); ?>"><?php bloginfo( 'description' ); ?></div>
<?php if ( get_header_image() ) : ?>
<img src="<?php header_image(); ?>" alt="">
<?php endif; ?>
</div>
<?php
}
/**
* Public output for header image
*
* #return void
*/
public function public_callback() {
$custom_callback = apply_filters( 'refur_custom_header_showcase_callback', false );
if ( false !== $custom_callback ) {
echo $custom_callback;
return true;
}
$this->open_image_wrap();
$this->show_image();
$this->show_slogan();
$this->close_image_wrap();
}
/**
* Open HTML wrapper for header image block
*
* #return void
*/
public function open_image_wrap() {
$subpage = '';
if ( ! $this->is_showcase() ) {
$subpage = ' is-subpage';
}
echo '<div class="header-showcase' . $subpage . '">';
}
public function show_image() {
$image = get_header_image();
$data = get_custom_header();
$alt = get_bloginfo( 'name' );
if ( ! $image ) {
return;
}
printf(
'<img src="%s" class="header-showcase_img" alt="%s" width="%s" height="%s">',
$image, $alt, $data->width, $data->height
);
}
/**
* Show header showcase content
*
* #return void
*/
public function show_slogan() {
if ( ! $this->is_showcase() ) {
return;
}
$title = refur_get_option( 'header_slogan_title', $this->default_settings['header_slogan_title'] );
$text = refur_get_option( 'header_slogan_text', $this->default_settings['header_slogan_text'] );
?>
<div class="header-showcase_content">
<div class="container">
<?php if ( $title || $text ) : ?>
<div class="header-showcase_slogan">
<?php if ( $title ) : ?>
<div class="header-showcase_title"><?php
echo wp_kses( $title, wp_kses_allowed_html( 'post' ) );
?></div>
<?php endif; ?>
<?php if ( $text ) : ?>
<div class="header-showcase_text"><?php
echo wp_kses( $text, wp_kses_allowed_html( 'post' ) );
?></div>
<?php endif; ?>
</div>
<?php endif; ?>
<?php $this->show_button(); ?>
</div>
</div>
<?php
}
/**
* Show header showcase call to action button
*
* #return void
*/
public function show_button() {
$text = refur_get_option( 'header_button_text', $this->default_settings['header_button_text'] );
$url = refur_get_option( 'header_button_url', $this->default_settings['header_button_url'] );
if ( ! $text ) {
return;
}
printf( '%1$s', esc_textarea( $text ), esc_url( $url ) );
}
/**
* Close HTML wrapper for header image block
*
* #return void
*/
public function close_image_wrap() {
echo '</div>';
}
/**
* Is showcase area visible on current page
*
* #return boolean
*/
public function is_showcase() {
if ( null !== $this->is_showcase ) {
return $this->is_showcase;
}
$this->is_showcase = ( is_front_page() && ! is_paged() ) ? true : false;
return $this->is_showcase;
}
/**
* Styles the header image and text displayed on the blog
*
* #see custom_header_setup().
*/
function header_style() {
// If we get this far, we have custom styles. Let's do this.
?>
<style type="text/css">
<?php
$mask_bg = refur_get_option( 'header_mask_color', $this->default_settings['header_mask_color'] );
$mask_opacity = refur_get_option( 'header_mask_fill', $this->default_settings['header_mask_fill'] );
$mask_opacity = absint( esc_attr( $mask_opacity ) ) / 100;
?>
.header-showcase:after {
background: <?php echo esc_attr( $mask_bg ); ?>;
opacity: <?php echo $mask_opacity; ?>;
}
</style>
<?php
}
/**
* Styles the header image displayed on the Appearance > Header admin panel.
*
* #see custom_header_setup().
*/
function admin_header_style() {
?>
<style type="text/css">
.appearance_page_custom-header #headimg {
border: none;
}
#headimg h1,
#desc {
}
#headimg h1 {
}
#headimg h1 a {
}
#desc {
}
#headimg img {
}
</style>
<?php
}
/**
* Header-related body classes
*
* #param array $classes
*/
public function add_body_classes( $classes ) {
if ( ! get_header_image() ) {
$classes[] = 'static-header';
}
if ( $this->is_showcase() ) {
$classes[] = 'showcase-active';
}
return $classes;
}
/**
* Returns the instance.
*
* #return object
*/
public static function get_instance() {
// If the single instance hasn't been set, set it now.
if ( null == self::$instance )
self::$instance = new self;
return self::$instance;
}
}
refur_custom_header::get_instance();
For part one: I'm not going to write all the code for you, but you can basically just find all the places in that file where you find header_slogan_title, header_slogan_text, and header_button_text and duplicate them judiciously.
For part two: you're going to want to hack this code in the file you linked to in your question:
/**
* Is showcase area visible on current page
*
* #return boolean
*/
public function is_showcase() {
if ( null !== $this->is_showcase ) {
return $this->is_showcase;
}
$this->is_showcase = ( is_front_page() && ! is_paged() ) ? true : false;
return $this->is_showcase;
}
Most likely you will want to change
$this->is_showcase = ( is_front_page() && ! is_paged() ) ? true : false;
to
$this->is_showcase = is_page();
or some other combination of template tags that produces true for the pages you want it to show for and false for the others.

How to Display Post Type with Page Template

I need to know how to pull all of my posts from a custom post type into a single page, while making the page display these posts according to the page template that is chosen in the post editor.
I integrated a dropdown that assigns page templates that can be chosen by the client, but how do I output that content?
Here's all the code for the post type, including the template chooser.
add_action('init', 'create_modules');
function create_modules() {
$moduleslabels = array(
'name' => 'Module',
'singular_name' => 'Home Module',
'add_new' => 'Add New Module',
'add_new_item' => 'Add New Module',
'edit_item' => 'Edit Module',
'new_item' => 'New Module',
'all_items' => 'All Modules',
'view_item' => 'View Module',
'search_items' => 'Search Modules',
'not_found' => 'No Modules Found',
'not_found_in_trash' => 'No Modules Found in Trash',
'parent_item_colon' => '',
'menu_name' => 'Home Modules'
);
$modules_args = array(
'labels' => $moduleslabels,
'public' => true,
'show_ui' => true,
'capability_type' => 'page',
'order' => 'ASC',
'rewrite' => true,
'menu_icon' => 'dashicons-menu',
'supports' => array('title', 'editor', 'thumbnail', 'page-attributes', 'revisions')
);
register_post_type('modules',$modules_args);
}
// admin filters
add_filter("manage_edit_modules_columns", "modules_edit_columns");
add_action("manage_posts_custom_column", "modules_columns_display");
function modules_edit_columns($modules_columns){
$modules_columns = array(
"cb" => "<input type=\"checkbox\" />",
"title" => "Section Title",
"description" => "Section Content",
);
return $modules_columns;
}
function modules_columns_display($modules_columns){
switch ($modules_columns)
{
case "description":
the_content();
break;
}
}
// new title text in Module
add_filter( 'enter_title_here', 'modules_enter_title_here' );
function modules_enter_title_here( $message ){
global $post;
if( 'modules' == $post-> post_type ):
$message = 'Enter Title';
endif;
return $message;
}
/** Custom Post Type Template Selector **/
function cpt_add_meta_boxes() {
$post_types = get_post_types();
foreach( $post_types as $ptype ) {
if ( $ptype !== 'page') {
add_meta_box( 'cpt-selector', 'Attributes', 'cpt_meta_box', $ptype, 'side', 'core' );
}
}
}
add_action( 'add_meta_boxes', 'cpt_add_meta_boxes' );
function cpt_remove_meta_boxes() {
$post_types = get_post_types();
foreach( $post_types as $ptype ) {
if ( $ptype !== 'page') {
remove_meta_box( 'pageparentdiv', $ptype, 'normal' );
}
}
}
add_action( 'admin_menu' , 'cpt_remove_meta_boxes' );
function cpt_meta_box( $post ) {
$post_meta = get_post_meta( $post->ID );
$templates = wp_get_theme()->get_page_templates();
$post_type_object = get_post_type_object($post->post_type);
if ( $post_type_object->hierarchical ) {
$dropdown_args = array(
'post_type' => $post->post_type,
'exclude_tree' => $post->ID,
'selected' => $post->post_parent,
'name' => 'parent_id',
'show_option_none' => __('(no parent)'),
'sort_column' => 'menu_order, post_title',
'echo' => 0,
);
$dropdown_args = apply_filters( 'page_attributes_dropdown_pages_args', $dropdown_args, $post );
$pages = wp_dropdown_pages( $dropdown_args );
if ( $pages ) {
echo "<p><strong>Parent</strong></p>";
echo "<label class=\"screen-reader-text\" for=\"parent_id\">Parent</label>";
echo $pages;
}
}
// Template Selector
echo "<p><strong>Template</strong></p>";
echo "<select id=\"cpt-selector\" name=\"_wp_page_template\"><option value=\"default\">Default Template</option>";
foreach ( $templates as $template_filename => $template_name ) {
if ( $post->post_type == strstr( $template_filename, '-', true) ) {
if ( isset($post_meta['_wp_page_template'][0]) && ($post_meta['_wp_page_template'][0] == $template_filename) ) {
echo "<option value=\"$template_filename\" selected=\"selected\">$template_name</option>";
} else {
echo "<option value=\"$template_filename\">$template_name</option>";
}
}
}
echo "</select>";
// Page order
echo "<p><strong>Order</strong></p>";
echo "<p><label class=\"screen-reader-text\" for=\"menu_order\">Order</label><input name=\"menu_order\" type=\"text\" size=\"4\" id=\"menu_order\" value=\"". esc_attr($post->menu_order) . "\" /></p>";
}
function save_cpt_template_meta_data( $post_id ) {
if ( isset( $_REQUEST['_wp_page_template'] ) ) {
update_post_meta( $post_id, '_wp_page_template', $_REQUEST['_wp_page_template'] );
}
}
add_action( 'save_post' , 'save_cpt_template_meta_data' );
function custom_single_template($template) {
global $post;
$post_meta = ( $post ) ? get_post_meta( $post->ID ) : null;
if ( isset($post_meta['_wp_page_template'][0]) && ( $post_meta['_wp_page_template'][0] != 'default' ) ) {
$template = get_template_directory() . '/' . $post_meta['_wp_page_template'][0];
}
return $template;
}
add_filter( 'single_template', 'custom_single_template' );
/** END Custom Post Type Template Selector **/
I don't have anything in terms of a page template yet, that's what I need help creating, but here's the post type code.
Thanks!
Using the right filter
The single_template filter is hookable when someone views a single item. Since you're looking to create a page with an overview of all the modules you should replace the filter you're now using (single_template) with another one - replace the last sentence of your code with:
add_filter( 'page_template', 'custom_single_template' );
Create a new page in the backend
Create a new page and name it 'Modules Page'. Select a page template from your custom drop down. Remember what page template you've selected. You'll need that in the following step.
Edit the page template
Fetching posts can be done with WP_Query. Try to paste the following code in the page template you selected in the above step, and see if you get results. Make sure you've added a couple of items in the modules post type.
// WP_Query arguments
$args = array (
'post_type' => array( 'modules' ),
'post_status' => array( 'publish' ),
'posts_per_page' => '-1',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
// get post data
$query->the_post();
// show the module title
echo get_the_title();
}
} else {
// no modules found
echo 'No items in "modules" post type';
}
// Restore original Post Data
wp_reset_postdata();

Custom Post Type templates not found

I have created a custom post type for cars which I have bootstraped off this tutorial. I am having a problem where I am getting 404 returned instead of archive-car.php and single-car.php. I have also tried to add the plural versions to the template names, however, no success. What could be wrong? Am I missing something?
<?php
if( ! function_exists( 'quote_create_post_type' ) ) :
function quote_create_post_type() {
$labels = array(
'name' => 'Cars',
'singular_name' => 'Car',
'add_new' => 'Add Car',
'all_items' => 'All Cars',
'add_new_item' => 'Add Car',
'edit_item' => 'Edit car',
'new_item' => 'New car',
'view_item' => 'View car',
'search_items' => 'Search cars',
'not_found' => 'No cars found',
'not_found_in_trash' => 'No cars found in trash',
'parent_item_colon' => 'Parent car'
//'menu_name' => default to 'name'
);
$args = array(
'labels' => $labels,
'public' => true,
'has_archive' => true,
'publicly_queryable' => true,
'query_var' => true,
'rewrite' => true,
'capability_type' => 'post',
'hierarchical' => false,
'supports' => array(
'title',
'editor',
'excerpt',
'thumbnail',
//'author',
//'trackbacks',
//'custom-fields',
//'comments',
'revisions',
//'page-attributes', // (menu order, hierarchical must be true to show Parent option)
//'post-formats',
),
'menu_position' => 5,
'exclude_from_search' => true,
'register_meta_box_cb' => 'quote_add_post_type_metabox'
);
register_post_type( 'car', $args );
//flush_rewrite_rules();
register_taxonomy( 'quote_category', // register custom taxonomy - category
'car',
array(
'hierarchical' => true,
'labels' => array(
'name' => 'Brands',
'singular_name' => 'Brand',
)
)
);
}
add_action( 'init', 'quote_create_post_type' );
function quote_add_post_type_metabox() { // add the meta box
add_meta_box( 'quote_metabox', 'Car Details', 'quote_metabox', 'car', 'normal' );
}
function quote_metabox() {
global $post;
// Noncename needed to verify where the data originated
echo '<input type="hidden" name="quote_post_noncename" value="' . wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
// Get the data if its already been entered
$quote_post_name = get_post_meta($post->ID, '_quote_post_name', true);
$quote_post_desc = get_post_meta($post->ID, '_quote_post_desc', true);
// Echo out the field
?>
<table class="form-table">
<tr>
<th>
<label>Brand</label>
</th>
<td>
<input type="text" name="quote_post_name" value="<?php echo $quote_post_name; ?>">
<!-- classes: .small-text .regular-text .large-text -->
</td>
</tr>
<tr>
<th>
<label>Description</label>
</th>
<td>
<textarea name="quote_post_desc" class="large-text"><?php echo $quote_post_desc; ?></textarea>
</td>
</tr>
</table>
<?php
}
function quote_post_save_meta( $post_id, $post ) { // save the data
/*
* We need to verify this came from our screen and with proper authorization,
* because the save_post action can be triggered at other times.
*/
if ( ! isset( $_POST['quote_post_noncename'] ) ) { // Check if our nonce is set.
return;
}
if( !wp_verify_nonce( $_POST['quote_post_noncename'], plugin_basename(__FILE__) ) ) { // Verify that the nonce is valid.
return $post->ID;
}
// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if( !wp_verify_nonce( $_POST['quote_post_noncename'], plugin_basename(__FILE__) ) ) {
return $post->ID;
}
// is the user allowed to edit the post or page?
if( ! current_user_can( 'edit_post', $post->ID )){
return $post->ID;
}
// ok, we're authenticated: we need to find and save the data
// we'll put it into an array to make it easier to loop though
$quote_post_meta['_quote_post_name'] = $_POST['quote_post_name'];
$quote_post_meta['_quote_post_desc'] = $_POST['quote_post_desc'];
// add values as custom fields
foreach( $quote_post_meta as $key => $value ) { // cycle through the $quote_post_meta array
// if( $post->post_type == 'revision' ) return; // don't store custom data twice
$value = implode(',', (array)$value); // if $value is an array, make it a CSV (unlikely)
if( get_post_meta( $post->ID, $key, FALSE ) ) { // if the custom field already has a value
update_post_meta($post->ID, $key, $value);
} else { // if the custom field doesn't have a value
add_post_meta( $post->ID, $key, $value );
}
if( !$value ) { // delete if blank
delete_post_meta( $post->ID, $key );
}
}
}
add_action( 'save_post', 'quote_post_save_meta', 1, 2 ); // save the custom fields
endif; // end of function_exists()
if( ! function_exists( 'view_quotes_posts' ) ) : // output
function view_quotes_posts($do_shortcode = 1, $strip_shortcodes = 0 ) {
$args = array(
'posts_per_page' => 10,
'offset' => 0,
//'category' => ,
'orderby' => 'menu_order, post_title', // post_date, rand
'order' => 'DESC',
//'include' => ,
//'exclude' => ,
//'meta_key' => ,
//'meta_value' => ,
'post_type' => 'car',
//'post_mime_type' => ,
//'post_parent' => ,
'post_status' => 'publish',
'suppress_filters' => true
);
$posts = get_posts( $args );
$html = '';
foreach ( $posts as $post ) {
$meta_name = get_post_meta( $post->ID, '_quote_post_name', true );
$meta_desc = get_post_meta( $post->ID, '_quote_post_desc', true );
$img = get_the_post_thumbnail( $post->ID, 'medium' );
if( empty( $img ) ) {
$img = '<img src="'.plugins_url( '/img/default.png', __FILE__ ).'">';
}
if( has_post_thumbnail( $post->ID ) ) {
$img = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail' );
$img_url = $img[0];
//the_post_thumbnail( 'thumbnail' ); /* thumbnail, medium, large, full, thumb-100, thumb-200, thumb-400, array(100,100) */
}
$content = $post->post_content;
if( $do_shortcode == 1 ) {
$content = do_shortcode( $content );
}
if( $strip_shortcodes == 1 ) {
$content = strip_shortcodes( $content );
}
$content = wp_trim_words( $content, 30, '...');
$content = wpautop( $content );
$html .= '
<div>
<h3>'.$post->post_title.'</h3>
<div>
<p>Name: '.$meta_name.'</p>
<p>Description: '.$meta_desc.'</p>
</div>
<div>'.$img.'</div>
<div>'.$content.'</div>
</div>
';
}
$html = '<div class="wrapper">'.$html.'</div>';
return $html;
}
endif; // end of function_exists()
?>
Further Info
All I am doing is extending the TwentyFifteen theme.
If I had to put money on this, I would say that you have not updated your permalinks! Simply go to Settings >> Permalinks >> Post Name.
The codex provides a little more information:
Note: In some cases, the permalink structure must be updated in order for the new template files to be accessed when viewing posts of a custom post type. To do this, go to Administration Panels > Settings > Permalinks, change the permalink structure to a different structure, save the changes, and change it back to the desired structure.

Categories