integrating twitter feed into a shortcode for wordpress - php

I'm trying to create a simple shortcode for wordpress that has the following variables:
- username
- no_of_tweets
So a user could write [twitter_feed username="USERNAME" no_of_tweets="5"]
and it displays a list of 5 of their latest tweets. I have been using a plugin called Twitter Feed for developers - it does all the oAuth stuff and the idea is that you just write the code to output some front end html.
I have it working except for one annoying glitch - I can't get the no_of tweets to work.
This code works, but doesn't allow for users to specify the no_of_tweets variable:
extract( shortcode_atts(
array(
'username' => 'skizzar_sites',
'no_of_tweets' => '3',
), $atts )
);
// Code
$tweets = getTweets(3, $username);
...
If I were tochange the code to the following (i.e. change the "3" in the $tweets variable, the code stops working:
extract( shortcode_atts(
array(
'username' => 'skizzar_sites',
'no_of_tweets' => '5',
), $atts )
);
// Code
$tweets = getTweets($no_of_tweets, $username);
Is there any reason why this might not be working correctly?
See full code below:
<?php
// Add Shortcode
function skizzar_twitter_feed( $atts ) {
// Attributes
extract( shortcode_atts(
array(
'username' => 'skizzar_sites',
'no_of_tweets' => '5',
), $atts )
);
// Code
$tweets = getTweets($no_of_tweets, $username);//change number up to 20 for number of tweets
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'];
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);
}
}
if(is_array($tweet['entities']['hashtags'])){
foreach($tweet['entities']['hashtags'] as $key => $hashtag){
$the_tweet = preg_replace(
'/#'.$hashtag['text'].'/i',
'#'.$hashtag['text'].'',
$the_tweet);
}
}
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;
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></a></li>
<li><a class="retweet" href="https://twitter.com/intent/retweet?tweet_id='.$tweet['id_str'].'"><i class="fa fa-retweet"></i></a></li>
<li><a class="favorite" href="https://twitter.com/intent/favorite?tweet_id='.$tweet['id_str'].'"><i class="fa fa-star"></i></a></li>
</ul>';
echo '
<p class="timestamp">
<a href="https://twitter.com/'.$username.'/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 '.$username.'\'S Twitter feed';
}
}
}
}
add_shortcode( 'twitter_feed', 'skizzar_twitter_feed' );
Here is the getTweets function code:
/* implement getTweets */
function getTweets($username = false, $count = 20, $options = false) {
$config['key'] = get_option('tdf_consumer_key');
$config['secret'] = get_option('tdf_consumer_secret');
$config['token'] = get_option('tdf_access_token');
$config['token_secret'] = get_option('tdf_access_token_secret');
$config['screenname'] = get_option('tdf_user_timeline');
$config['cache_expire'] = intval(get_option('tdf_cache_expire'));
if ($config['cache_expire'] < 1) $config['cache_expire'] = 3600;
$config['directory'] = plugin_dir_path(__FILE__);
$obj = new StormTwitter($config);
$res = $obj->getTweets($username, $count, $options);
update_option('tdf_last_error',$obj->st_last_error);
return $res;
}

Related

Codeigniter safest way of making update function with id on a hidden field

What's the safest way to do a function update having a hidden html input containing the id of the data?
<input type="text" name="request_id" value="<?php echo $param_request['idx']?>" style="display: none;">
Form validation is already included in my code and that's for making sure that all fields are required.
But how do I prevent someone from altering the hidden field (id)? What do I need to add in my update function in the controller for better security?
Here is my function in the controller:
public function update()
{
$this->load->library('form_validation');
$form_data = $this->input->post();
$idx = $this->input->post('request_id');
$form_request_type = $this->input->post('request_type');
$form_leave_start = $this->input->post('form-leave-start');
$form_leave_end = $this->input->post('form-leave-end');
$form_date_needed = $this->input->post('form-date-needed');
$form_amount_needed = $this->input->post('form-amount-needed');
$form_remarks = $this->input->post('redactor-textarea');
$form_refer = $this->input->post('refer');
$this->form_validation->set_data($form_data);
$this->form_validation->set_rules('refer[]', 'refer', 'required');
foreach ($form_data as $name=>$value) {
if($name!='refer'){
$this->form_validation->set_rules($name, $name, 'required');
}
}
//Checkboxes
$refer = json_encode($form_refer);
//Not common contents
$contents_info = json_encode(array(
'leave_start_date' => $form_leave_start,
'leave_end_date' => $form_leave_end,
'date_needed' => $form_date_needed,
'amount_needed' => $form_amount_needed,
'remarks' => $form_remarks
));
//Common contents
$common_info = array(
'requested_by_idx' => $this->session->userdata('member_index'),
'request_type' => $form_request_type,
'date_updated' => date("Y-m-d H:i:s A"),
'contents' => $contents_info,
'refer' => $refer,
'status' => 'PENDING'
);
$log = array(
'controller'=>'request',
'method'=>'update',
'item_idx'=>0,
'member_idx'=>$this->session->userdata('member_index'),
'member_category'=>$this->session->userdata('member_category')
);
$ret = $this->staffrequisition_model->updateItem($common_info, array('idx'=>$idx), $log);
echo json_encode(array('ret'=>($ret == true) ? 1 : 0));
}
And also I loaded the update view using an anchor tag with the id send in the link:
<i class="fa fa-edit"></i> Update
Receiving function:
public function update_request_view($idx)
{
$data = new stdClass;
$data->param_menu = 'request';
$type = $this->staffrequisition_model->getRequestType($idx);
$typeLower = strtolower($string = str_replace(' ', '', $type));
$commonContents = $this->staffrequisition_model->selectItem(array('idx'=> $idx));
$uncommonContents = json_decode($commonContents->contents);
$data->param_request = array_merge((array) $commonContents, (array) $uncommonContents);
$data->param_request_type = $type;
$data->param_refer = json_decode($data->param_request['refer']);
$this->load->view('dashboard/staff/update_'.$typeLower.'_view', $data);
}

Wordpress PHP query is pulling the wrong database entry

first question here!
I have a custom wordpress site in which I have a check out function that includes a discount/coupon code.
I have done the following to test the code:
- I have set-up three coupon codes in my database
- All three coupon codes are in the database with the correct information
When I try to input a coupon, the code is only applying the coupon rules of the last coupon entered. It should instead by pulling the coupon code that matches the user input of $couponcode
I know there is something wrong with the way I'm assigning the $couponID but I can't figure out how to do it correctly.
Note: I am aware of the mis-spelling of: cooupon_title. however it's set-up this way in the database, so that's not the error.
<?php
$couponCode = '';
$couponMessage = '';
$discountAmount = 0;
$couponId = 0;
if(isset($_POST['couponCode']) && !empty($_POST['couponCode'])) {
$couponCode = $_POST['couponCode']; }
if(!empty($couponCode)) {
$args = array('posts_per_page' => 1,'offset' => 0,'category' => '', 'category_name' => '', 'orderby' => 'date','order' => 'DESC','include' => '', 'exclude' => '','meta_key' => '','meta_value' => '','post_type' => 'coupons','post_mime_type' => '','title' => $couponCode,'post_status' => 'publish','suppress_filters' => 'true');
$couponDbData = get_posts($args);
$couponResultData = '';
if(isset($couponDbData[0]) && !empty($couponDbData[0])) {
$couponResultData = $couponDbData[0];
} else {
$couponMessage = 'Invalid coupon code';
}
if(isset($couponResultData->ID) && !empty($couponResultData->ID))
$couponId = $couponResultData->ID;
if(!empty($couponId)) {
$expiry_condition = get_post_meta($couponId,'expiry_condition',true);
$expiry_value = get_post_meta($couponId,'expiry_value',true);
$no_of_use = get_post_meta($couponId,'no_of_use',true);
$appyCoupon = false;
if($expiry_condition=='use') {
if($expiry_value > $no_of_use) {
$appyCoupon = true;
} else {
$couponMessage = 'Coupon has expired.';
}
} else {
$couponExpireTime = strtotime($expiry_value);
$currentTime = time();
if($couponExpireTime > $currentTime) {
$appyCoupon = true;
} else {
$couponMessage = 'Coupon has expired.';
}
}
if($appyCoupon) {
$cooupon_title = get_post_meta($couponId,'cooupon_title',true);
$coupon_type = get_post_meta($couponId,'coupon_type',true);
$coupon_value = get_post_meta($couponId,'coupon_value',true);
if($coupon_type=='$') {
$discountAmount = $coupon_value;
} else {
$discountAmount = ($orderAmount*$coupon_value)/100;
}
$grandTotal -= $discountAmount;
}
}
}
this is my test output:
if($appyCoupon) { ?>
<div class="col-sm-12 col-md-12 makeOrderDetailsrow">
<label class="col-sm-4 col-md-4">Discount <?php echo '( Apply coupon '.$couponCode.' from the following sources '.$couponId.' '.$cooupon_title.' '.$coupon_value.' '.$coupon_type.')'; ?></label>
<span class="col-sm-8 col-md-8">- $<?php echo (number_format($discountAmount,2)); ?></span>
</div>
The output after "from the following sources" shows the code is pulling the last entry in the DB rather than the one that matches the $couponCode. Any advice or suggestions? thank you
According to the codex, the args for get_posts does not include 'title', https://codex.wordpress.org/Template_Tags/get_posts.
Wordpress has a function to query the post by the title, get_page_by_title( $page_title, $output, $post_type );http://codex.wordpress.org/Function_Reference/get_page_by_title
By the way, you don't have to include the whole list of $args in the get_posts query, just those you want to change from the default. For example,
$args = array(
'post_type' => 'coupon',
);
Will override the default of 'post_type' => 'post', without changing 'posts_per_page' => 5.

Adding html to t() in Drupal 6 template.php?

Hi I am trying to add html to the "t('Older Posts')" and "t('Newer Posts')" Is this possible ? I can figure it out ????
I am in a Drupal 6 template.php file.
This is the code I am trying to add as html -
<span>Newer Posts</span>
<span>Older Posts</span>
I need to replace the above in these spots located in the full function below ?
t('Older Posts')
t('Newer Posts')
I want to create something like this
t('<span>Older Posts</span>')
t('<span>Newer Posts</span>')
Full Function
function theme_views_mini_pager($tags = array(), $limit = 10,
$element = 0, $parameters = array(), $quantity = 9) {
global $pager_page_array, $pager_total;
// Calculate various markers within this pager piece:
// Middle is used to "center" pages around the current page.
$pager_middle = ceil($quantity / 2);
// current is the page we are currently paged to
$pager_current = $pager_page_array[$element] + 1;
// max is the maximum page number
$pager_max = $pager_total[$element];
// End of marker calculations.
$li_previous = theme('pager_previous', (isset($tags[1]) ? $tags[1] :
t('Older Posts')), $limit, $element, 1, $parameters);
if (empty($li_previous)) {
$li_previous = " ";
}
$li_next = theme('pager_next', (isset($tags[3]) ? $tags[3] : t('Newer Posts')),
$limit,$element, 1, $parameters);
if (empty($li_next)) {
$li_next = " ";
}
if ($pager_total[$element] > 5) {
$items[] = array(
'class' => 'action back pager-previous',
'data' => $li_previous,
);
$items[] = array(
'class' => 'action pager-next',
'data' => $li_next,
);
return theme('item_list', $items, NULL, 'ul', array('class' => 'pager'));
}
}
I am trying to figure out if this is possible I have tried many things and nothing has worked yet.
You can use
$link = '<span>' . t('Older Posts') . '</span>';
OR
$link = t('!link_startOlder Posts!link_end', array(
'!link_start' => '<a href="" class="action back"><span>',
'!link_end' => '</span></a>',
));

Calling a function within foreach?

I've been working on a Wordpress theme project over the past few days and I've been stuck on how to get a dynamic options page running properly using OOP (I'm primarily a Theme Developer, not a PHP scripter).
<?php
$footerpage = new optionpage;
$footerpage->title = 'Footer';
$footerpage->titleprint = ' Footer Options';
$footerpage->slug = 'footer';
$footerpage->html = array(
'1' => array(
'type' => 'textarea',
'class' => 'large-text',
'name' => 'html',
'title' => 'HTML',
'description' => 'Type in whatever HTML you\'d like to see in the footer here:',
),
'2' => array(
'type' => 'input',
'class' => 'large-text',
'name' => 'background-color',
'title' => 'Background Color',
'description' => ' Choose a Background Color:'
),
);
class optionpage {
public $title;
public $titleprint;
public $slug;
public $html = array();
......
......
......
public function ab_settings() {
register_setting( $this->slug, 'ab_options');
add_settings_section('ab_section', '', array(&$this, 'ab_do_titleprint'), 'ab_' . $this->slug . '_options', 'ab_options' );
foreach ($this->html as $key => $html) {
add_settings_field( $key, $html['title'], array(&$this, 'ab_do_htmlprint' ), 'ab_' . $this->slug . '_options', 'ab_section');
}
}
public function ab_do_htmlprint() {
$html = $this->html[$key];
?>
<p><?php echo $html['description'] ?></p>
<<?php echo $html['type'] ?>
id="<?php echo $html['id'] ?>"
class="<?php echo $html['class'] ?>"
name="<?php echo $html['name'] ?>">
<?php get_option ($html['name'])?>
</<?php echo $html['type'] ?>>
<?php
}
......
......
?>
In this code example, I'm trying to get the function ab_do_htmlprint to recognize the foreach expressions where it's been called, because the function is going to be called as many times as needed in the foreach loop.
I've tried several things, like appending a variable to the function name, but that would require multiple functions of the same code, just with a different name. I also tried passing various variables by reference and such, however they weren't working either, and I may not have been doing that correctly, if they're even needed.
Anyway to accomplish this efficiently?
If I understand correctly you have an array of values that you want to show in a group on the admin screen as options.
Maybe the shortest example is what i posted here: http://swiftthemes.com/forums/showthread.php?383-SWIFT-on-a-WordPRess-MU-install/page2
p.s. post WordPress questions on http://wordpress.stackexchange.com : more WordPress Experts!
If I understand correctly, you need to pass an argument to ab_do_htmlprint. add_settings_field has parameter for that, do:
add_settings_field( $key, $html['title'], array(&$this, 'ab_do_htmlprint' ), 'ab_' . $this->slug . '_options', 'ab_section', array($key));
then:
public function ab_do_htmlprint($key) {
$html = $this->html[$key];
etc.
I am not familiar with the Wordpress api, so please verify a few assumptions I have. (I know this is not an answer, but I do not want to put as a comment for readability)
1) ab_settings() is called somewhere?
2) Is the section you are having issues with?
foreach ($this->html as $key => $html) {
add_settings_field( $key, $html['title'], array(&$this, 'ab_do_htmlprint' ),
'ab_' . $this->slug . '_options', 'ab_section');
}
3) $key is magically available or do you need to provide it as an argument?
public function ab_do_htmlprint() {
$html = $this->html[$key];`
Also, the format of your ab_do_htmlprint function is very hard to read and could be a source of error. Try using HEREDOC notation or purely PHP strings
ex) Instead of
public function ab_do_htmlprint() {
$html = $this->html[$key];
?>
<p><?php echo $html['description'] ?></p>
<<?php echo $html['type'] ?>
id="<?php echo $html['id'] ?>"
class="<?php echo $html['class'] ?>"
name="<?php echo $html['name'] ?>">
<?php get_option($html['name'])?>
</<?php echo $html['type'] ?>>
<?php
}
as
public function ab_do_htmlprint() {
$html = $this->html[$key];
$output = "<p>{$html['description']}</p>";
$output .= "<{$html['type']} id=\"{$html['id']}\"";
$output .= " class=\"{$html['class']}\"";
$output .= " name=\"{$html['name']}\">";
get_option( $html['name'] );
$output .= "</{$html['type']}>";
echo $output;
}

How do I assign a unique static string for each item generated in a for loop?

How do I assign unique static strings to a variable in a for loop? I'm trying assign a unique description and alt tag to a list of thumbnails. I have managed to get the loop to produce the thumbnails but I cannot work out how to assign unique values to each one based on the condition of the value. This is the for loop:
<?php
for ( $project=1; $project<=40; $project++ ) {
echo "
<a href=\"#\" class=\"thumb\">
<img src=\"images/thumbs/$project.jpg\" width=\"300\" height=\"140\" alt=\"$projectname\" title=\"$projectname\" />
<span class=\"client\">$projectname</span><span class=\"description\">$type</span>
</a>
";
}
?>
I tried this before the for loop but didn't work...
if ( $project = 1 ) {
$projectname = "client1";
$type = "Interactive Brochure Design";
}
else if ( $project = 2 ) {
$projectname = "client2";
$type = "Site Design";
}
if ( $project == 1 ) {
$projectname = "client1";
$type = "Interactive Brochure Design";
}
else if ( $project == 2 ) {
$projectname = "client2";
$type = "Site Design";
}
= sets a variable and doesnt compare. == compares
of course there are probably more elegant ways for your project...
You would usually begin with storing each project in an array, so you can easily loop through them. The values stored in the array could be objects of some "project" class, or an associative array, like this:
$projects = array(
array(
'name' => 'client1',
'type' => 'Interactive Brochure Design',
'filename' => 'client1.jpg',
),
array(
'name' => 'client2',
'type' => 'Site Design',
'filename' => 'client2.jpg',
),
);
foreach($projects as $project)
echo '
<a href="#" class="thumb">
<img src="images/thumbs/'.$project['filename'].'" width="300" height="140" alt="'.$project['name'].'" title="'.$project['name'].'" />
<span class="client">'.$project['name'].'</span><span class="description">'.$project['type'].'</span>
</a>
';
That's what arrays are there for. Something like:
$projects = array(
array('name' => 'client1', 'type' => 'Interactive Brochure Design'),
array('name' => 'client2', 'type' => 'Site Design'),
);
for ($n=0; $n<count($projects); ) {
$projectname = $projects[$n]['name'];
$type = $projects[$n]['type'];
$project = ++$n;
echo "
<a href=\"#\" class=\"thumb\">
<img src=\"images/thumbs/$project.jpg\" width=\"300\" height=\"140\" alt=\"$projectname\" title=\"$projectname\" />
<span class=\"client\">$projectname</span><span class=\"description\">$type</span>
</a>
";
}
Or you could also use foreach:
foreach ($projects as $project) {
echo '<div>name: ' . $project['name'] . '</div>
<div>type: ' . $project['type'] . '</div>';
}
See it on codepad

Categories