Categorie ‘PHP’ » Archiv


6

How to fix radio inputs losing focus when dragging a jquery ui sortable div

July
24

hows that for a descriptive title eh? haha, that’s the exact term I used when I ran into trouble with some wordpress meta boxes on a custom admin page I was making for the new CommentLuv. I am using the WordPress functions for add_meta_box to add, you guessed it, meta boxes to a settings page.

Draggable killed the radio bar

ok, lame Queen song title parody I know but it’s true. I had a bar of radio buttons in one of those meta boxes and if I dragged and dropped the box to a new place, it lost it’s radio button dots!

When I dropped the sortable meta box, the happy little dot in the radio input would disappear which messed things up when I saved the settings because the form would not have a radio input with a status of checked any more. :-(

jQuery rescues jQuery!

jQuery is frickin awesome and I love it. It’s the sole reason CommentLuv was able to become the plugin it is today. It’s also sometimes a little finicky and it does things in a particular way which causes some mild issues. This is one of them, it’s all due to jQuery cloning the contents of the sortable box when you drag it and then when you drop it, the radio button loses it’s happy little dot.

I did a mammoth amount of searching and could only find 2 instances of it happening elsewhere (here and here) and both instances said it was a bug/feature and didn’t provide a solution.

Geek me up, I’m goin in!

[youtube clip_id="Z9_jIa2WADc"/]

As a means to procrastinate, an unhealthily strong stubbornness bone and a burning sensation in my pants whenever I can’t do something that I want to do, I set about trying some code to re click the radio buttons after the meta box had been dropped after dragging.

Here it is, I hope you find it useful! (change the two instances of .wrap to whatever container your sortables are in)

// global script for commentluv premium settings pages
// workaround for bug that causes radio inputs to lose settings when meta box is dragged.
// http://core.trac.wordpress.org/ticket/16972
jQuery(document).ready(function(){
    // listen for drag drop of metaboxes , bind mousedown to .hndle so it only fires when starting to drag
    jQuery('.hndle').mousedown(function(){
        // set event listener for mouse up on the content .wrap and wait a tick to give the dragged div time to settle before firing the reclick function
        jQuery('.wrap').mouseup(function(){store_radio(); setTimeout('reclick_radio();',50);});
    })
});
/**
* stores object of all radio buttons that are checked for entire form
*/
function store_radio(){
    var radioshack = {};
    jQuery('input[type="radio"]').each(function(){
        if(jQuery(this).is(':checked')){
            radioshack[jQuery(this).attr('name')] = jQuery(this).val();
        }
        jQuery(document).data('radioshack',radioshack);
    });
}
/**
* detect mouseup and restore all radio buttons that were checked
*/
function reclick_radio(){
    // get object of checked radio button names and values
    var radios = jQuery(document).data('radioshack');
    //step thru each object element and trigger a click on it's corresponding radio button
    for(key in radios){
        jQuery('input[name="'+key+'"]').filter('[value="'+radios[key]+'"]').trigger('click');
    }
    // unbind the event listener on .wrap  (prevents clicks on inputs from triggering function)
    jQuery('.wrap').unbind('mouseup');
}

ajax, Code, jquery, PHP


1

Taming the Upgrades plugin from http://premium.wpmudev.org

February
2

If you’re lucky enough to have a subscription to Premium WPMU Dev account then you’ll have access to great monetization plugins like the Upgrades or Supporter which take all the pain out of providing a ‘pay for’ service that can handle payments through Paypal, Google or even Amazon gateways.

I downloaded and installed the upgrades plugin a while ago and I’ve used it to monetize certain parts of my ComLuv site. There’s the usual way of adding plugins to the Upgrades directory and configuring them to be used which I’ll go into in a future post but I wanted to use the system slightly differently, and that was to charge users for adding new URLs to an account or to add default links to their returned list of posts.

The advantage of premium

Some of the advantages to using wpmupremium plugins is the support you receive, knowledge that the plugin will be updated to keep it compatible with new changes and my favourite is, the quality of the code.

When you’re getting premium, you’re getting premium code which for me personally, has taught me a LOT about how wordpress works. Particularly custom hooks and actions and filters. That was always a mystery to me until I dissected the plugins I downloaded from their site so it was a breeze to modify the upgrades plugin to work for users who don’t have blogs and start using the internal functions in a daughter template to do what I wanted.

Modifying the upgrades plugin


I needed to allow the upgrades menu to show for regular users because not everyone who joins the Comluv site starts a blog. This was just a simple case of changing the user level so that everyone, not just blog owners can see the menu and buy credits.

There are two places to modify:

/mu-plugins/upgrades-framework.php
line ~ 197-200 (upgrades plug pages framework function)
change add menu and submenu calls to

add_menu_page($upgrades_branding_plural, $upgrades_branding_plural, 0, 'upgrades.php');
add_submenu_page('upgrades.php', __('Credits'), __('Credits'), 0, 'credits', 'upgrades_credits_output' );
add_submenu_page('upgrades.php', __('History'), __('History'), 0, 'history', 'upgrades_log_output' );

line ~ 1919 (upgrades_credits_output function)
change user check to

if(!current_user_can('level_0')) {

Creating the daughter template

Adding another page you can use as a template is pretty easy, you just need to create a new php file in your theme directory and make sure it has the correct remarks at the top to identify it as a template page.


/*
Template Name: ComLuv purchase url
*/

Next just copy and paste the main calls from another template, you’ll be deleting most of it like the loop to display posts and replacing it with your own hard coded form and text. Be sure to keep the divs that surround the content intact.

I wrote a description of the item being sold and added a form.
(DON’T copy and paste from this page, I had to remove the beginning < characters from the code so it displays properly)

form action='/member/additional-urls/' method="POST">
input name="addurl" type="text" size="30"/>
input type="submit" name="submit1" value="Submit"/>

/form>

I also added a finish_page() function which just closes the /div tags so I could easily break out of what I was displaying without rendering the rest of the custom code below it.

You set the action to the page slug you’re publishing the page as and put a nonce field in there so you can check it with the next bit of code to prevent a naughty user from trying to call the purchase directly.

Handling the purchase

Next, you need to handle the data that gets submitted by your form and do the magic with the users credits.

if(isset($_POST['submit1'])){
$nonce=$_REQUEST['_wpnonce'];
if(!wp_verify_nonce($nonce,'addurl1')){
echo 'Page request deformed, please go back and try again. (b1s1)';
finish_page();
}
if(!$_POST['addurl']){
echo 'Please go back and enter a value';
finish_page();
}
// check if user has enough credits
global $user_ID;
$credits = upgrades_user_credits_available($user_ID);
if($credits < 3){
echo 'h2>Error - Insufficient Credits/h2>';
echo 'p>You will need to purchase some credits to register another URL, you currently have strong>'.$credits.'/strong>';
echo 'p>a href="/wp-admin/upgrades.php?page=credits">Click here to visit the purchase page/a>';
finish_page();
}
// if we're here then everything is ok to provide service and deduct credits
$credits = upgrades_user_credits_available($user_ID);
$credits -= 3;
upgrades_user_credits_update($credits);
upgrades_log_add_msg($user_ID,'You paid 3 credits for an additional URl - '.$url);
do_add_url($url,$user_ID);
echo 'h2>Site added, 3 credits used on your account/h2>';
echo 'p>You have '.$credits.' credits remaining';
echo 'p>a href="/member/additional-urls/">Click here to refresh the page/a>';

The first bit gets the nonce you created and checks it and displays an error message if it doesn’t match
Next, check the field you’re expecting and spit out an error if it is empty.
Next, check the user has enough credits and spit out an error if they don’t.
If everything is fine, continue.

use $credits = upgrades_user_credits_available($user_ID); to get the users current credits total
use upgrades_user_credits_update($credits); to set the users credits total to $credits (after you deduct what your item/upgrade costs)
use upgrades_log_add_msg($user_ID,’You paid 3 credits for an additional URl – ‘.$url); to add a message to the users Credits history page so they know they used some.

That’s it, easy peasy! Here’s an idea, use credits to sell digital downloads on another page, just check and deduct the users credits before allowing a dowload.

I’ll post a follow up to this soon on how to use the upgrades plugin to add a new package that enables the RSS widget for a blog (I’ll show you how to disable the rss widget too)

You can get over 100 plugins and themes of premium quality at http://premium.wpmudev.org and they all help to make your wpmu site better than the jones’s :)

Blog Tools, Making / Made Money, PHP, Wordpress


4

How to do a mass text search and replace with MySQL

October
24

I noticed that all my images on the posts here weren’t showing and it was because the url to their location was still pointing at the sub blog on The Comluv Network so I needed a way to edit the database to update the url to point to the files held here.

Easy with a REPLACE function on the wp_posts table.

You just need 3 things for the replace command :

  1. The row you’re altering
  2. The string you’re searching for
  3. The string you’re replacing with

UPDATE `wp_posts` SET `post_content` = REPLACE( `post_content` , "fiddyp.comluv.com/files/", "fiddyp.co.uk/wp-content/uploads/" )

It did the whole table of posts in less than a second. Sweet, now all my images are back to normal on this site.

Code, PHP


165

WP-Twitip-ID Plugin – Add a twitter field to your comment form (easily)

October
8

Version 1.0 (updated 11 Feb 09)
Requires: WordPress 2.6 (could work with lesser)
Tested up to : WordPress 2.7b3

This plugin is no longer supported, please download TwitterLink-Comments which will do a much better job and will still be able to use the existing database table and labels.

Download TwitterLink Comments

Blog News, Blog Tools, Code, PHP, Wordpress


1

A day of other peoples code

June
24

Support Tickets

I did some pretty fancy tweaking of code today to see if I can replace the support tickets system on ComLuv, the system at the moment isn’t bad but the last support ticket management software I used was far superior and allowed me to reply to closed tickets and create canned responses.

It will need some more work to integrate it into the dashboard of the site but I’m pretty confident I can do it.

Theme

I feel the need to tweak themes too, I found an old mockup image on my hard drive that I had for a client that never took up the job and I contacted someone about converting it to a WP theme. I love how it looks and I’d really like to have the format for ComLuv so I can start on tutorials and other features.

That’s not to say the current one isn’t great, it’s just that I’m all for “get it done” then “make it work” and then “make it pretty” and then “do it all again until I have what I want.

Newsletter

I had a bit of a nightmare with my newsletter software taking up too much resources while being on the same server as ComLuv so I took steps to transfer it to another server and use the ComLuv SMTP connection to do all the sending. Hopefully this will fix any issues I was seeing..

Tutorials & Videos

I have the new pc set up with a screen recorder and I have a list of videos that I’d like to produce for tutorials on the ComLuv site. I tested it out and my quad core monster can handle the capture on a widescreen so I can do HD videos and host them on Vimeo

Remote Images & Scripts

I have done some serious optimization on the blogger version of CommentLuv so that now there are very few calls to the ComLuv server for images and scripts. This one thing should dramatically decrease the server load during busy times.

Work

And now I have to tweak the system in the shop.  The tweaking never ends!

Blog News, PHP, Social Networking, Wordpress


2

Coding is nearly done for new CommentLuv for Blogger/Js-kit

June
11

enough with the twitter updates please mr. twittertools! sorry about that, who really needs to see twitter updates? (although i did notice google indexing more tweets and sending me alerts about them)

anyhoo, I am fiddling with some code right now for the Blogger / JS-kit version of new CommentLuv and will hopefully have that up ready for the weekend quiet time. I’ll put up some easy install instructions too so it should be case of click a button and the code gets installed to your blogger dashboard.

I’m hosting the script files myself on my ukfast server, the last server (when it stayed up) managed to serve those files ok so I think it should be fine for the switch on with this new super dedicated and supported server. If it gets too much, then I can look at using Amazons’ S3 service to serve everything. I researched on their service before and it seems to be fairly inexpensive to do. Although now, I’m paying for the server so I might as well use its resources. If things get so big that it needs a massive upgrade then that can be dealt with at the time. (Dragons Den? lol)

Please let me know about any errors you’re experiencing or glitches with the CommentLuv API, site or plugin by submitting a support ticket at The ComLuv Network

I still can’t believe how many hits and links come through to my sites from this plugin, last night there were over 1300 downloads of the plugin from the wordpress repository! and more than 1500 comments processed by the API.

Talking of the API, it is being updated before the weekend so I hope you can be patient, I am but one man and have only 2 coder peeps to pester/hassle/question/demand/poke/tweet about the server and API. And to top it off, I work full time in a takeaway (Fired Wok Chinese Takeaway and Delivery in Lancaster, Lancashire – tasty food chop chop!) which I luv. (seriously, I luv that job)

Blog News, Blog Tools, PHP


12

Getting ready to release new CommentLuv to the public

June
6

I’ve just created the new readme file to go with the plugin and intend to release it to the public on Monday!

This version does things a little differently like adding a little bit of data along with the link to the comment. The data is there to aid in accurate stats for when a comment gets deleted by the admin or if a visitor clicks on the link or views the info box.

It’s been working nicely over at ComLuv on the sub blogs with only a few minor style tweaks to get it working on all the themes I have over there, I’m going through the last bits of tweaking while it’s on here so I can make sure it plays nice with a single user blog too.

You can see it working by commenting on this post, if you’re already a commentluv member then it should be able to bring back your posts ok and if you’ve started a blog at ComLuv then you’ll be able to visit the site and add more sources to your returned posts by visiting the member page.

Don’t worry about any strangeness happening here over the weekend with comments, it’s just me fiddling with the code!

Blog News, PHP


5

Oh the chore of documentation and user error prevention

June
4

I love to create php scripts and plugins for wordpress, I love the feeling of acomplishment when something I have conceived turns into reality (and useful to boot!)

Whenever this happens my first reaction is to PUTITONTHENET! but, experience tells me that before I can do that, I need to go through the code and settings page and try every conceivable permutation of user input to see if it breaks the program. Problem is, as the code gets more and more complicated, the more options and different ways of using the program there are.

So, I have to do the best I can to test it on my own machine and on a few different servers I have spotted around the globe and if that works, send it out! Chances are that someone will find some new way to break it but, that’s how things get better (I keep telling myself)

Now I have to put some documentation up for new CommentLuv, the API, the ComLuv network and oh about a ton of other things and this post was a useful procrastination (makes you go blind you know!?).

Code, PHP


8

Having an issue with dbDelta to add table to wp db (resolved)

February
11

I’m having some issues with trying to put the WP-Twitip-ID plugin into the final version.

Right now, the beta version stores the twitter ID in the post meta for each post but that’s not really ideal because it can only show the twitter id on the comments of the post that the user has already commented on. New post comments require the user to add their twitter id again. Not too much trouble because if they have entered a twitter id in a previous comment then the plugin sets a cookie on their machine and adds it to the field when they comment again.

What I’d rather do is store the twitter id in the database so it’s accessible outside the post meta. I could store the id’s in wp_options but that would probably cause loading time issues because wp_options values get loaded automatically and considering the amount of comments a blog gets, it would bloat it out massively.

My solution is to create a new table on the database and add the twitter id and email address in there, that way I only have to update the db once when a new twitter id is entered.

The problem I am having is creating the table! for some reason, it’s not adding it. I’ve even copied and pasted another plugins code to do it and it still wont work!

here’s my code :

function atf_install() {
global $wpdb;
global $atf_db_version;
add_option("atf_db_version", $atf_db_version);

$table_name = $wpdb->prefix . "wptwitipid";
if($wpdb->get_var("show tables like '$table_name'") != $table_name) {
$sql = "CREATE TABLE " . $table_name . " (
id mediumint(9) NOT NULL AUTO_INCREMENT,
email varchar(120) NOT NULL,
twitid varchar(120) NOT NULL,
KEY email (email)
);";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
}
$atf_db_version = "1.0";
register_activation_hook(__FILE__, 'atf_install');

There’s a problem with the $atf_db_version too. It adds an option to wp_options for the key of “atf_db_version” but no value and it’s really starting to piss me off!

anyone out there in geek land that can help me here?

Fixed!!

A massive thanks to @clearskynet who answered and solved the problem within minutes of me posting this.

hurray!!

Code, PHP, Wordpress


5

Autumn Sun and Coding Fun

October
2

After a bright and early start to the day after my scrumptious chicken last night I felt good as the sun shone through my window and now, in the late afternoon, I’m done.

CommentLuv is now updated to 2.5, it incorporates the heart tip plugin as an optional extra and makes it compatible with wp2.5 too.

I spent most of the time separating the jquery and other scripts into include folders which makes the header source much tidier and the scripts themselves much easier to edit and update. The last 2 hours have been spent getting the tip box to work as part of commentluv and the result is activated here for testing.

I’ll let it settle in for a day or so and then do a codex update along with an update to the CommentLuv registered members to let them know about the site allowing them to edit their profile and have their description parsed and placed in the info boxes.

I made some minor changes to the code so that those who prefer the old style commentluv can have a checkbox to untick if the user doesn’t want the last post shown. Hopefully that will make it easier for the previous versions users to switch to the new one.

To celebrate, I’m off for a walk next to the canal with the missus
canal boats

edit… I had such a nice walk that I came up with some good ideas and my missus’ secret stealth plan to get us to end up in Oxford street gave me time to run them through my head until I could get back to the keyboard and add them in!

I have put in a bit of code that should make it work out of the box for most blogs, most of the questions I get on the forum are solved either by getting the person to change their comment form ID value or telling them that it is working but they can’t see the button and checkbox while they’re logged in as admin.

Now, the form id is found out automatically as long as the comment text area ID is correct and that should be because all wordpress blogs send their comment as POST variables which use the name attribute of the form and for that to work on all themes, all themes must use the same values for the name attribute.

If I know what they are then I can find out the parent form ID easily.

I’ve also added the checkbox and badge to show for admin so I no longer have to spend ages visiting peoples sites and viewing the source to let someone know how to get the plugin working.

this is really the best version out yet! I’ll update it on the codex tomorrow

ajax, Blog News, Blog Tools, Code, PHP