Showing posts with label Why not to copy and paste code mindlessly. Show all posts
Showing posts with label Why not to copy and paste code mindlessly. Show all posts

Thursday, May 2, 2013

Why not to copy and paste code mindlessly

While working to try and fix what was preventing the status messages from showing I came across a few things that were wrong and all come from copying and pasting code.  This is why I need to get better with writing in these languages rather than copy and paste shit because in the end I waste more time trying to fix the code.

I posted a link to a wordpress support forum where a user posted "working" code for retrieving a user id from a username: http://wordpress.org/support/topic/getting-user-id-from-username  The code I used from here was:
$user = get_userdatabylogin('admin');
var_dump($user);
echo $user->ID; // prints the id of the user


get_userdatabylogin (http://codex.wordpress.org/Function_Reference/get_userdatabylogin), is a deprecated function and was replaced with get_user_by (http://codex.wordpress.org/Function_Reference/get_user_by).  This wasn't what caused the error but it's always nice to be using updated code.

What was causing the error was the var_dumphttp://php.net/manual/en/function.var-dump.php
This is used to dump information about the variable but with the get_user_by function I surely don't need it and when I took it out and ran it with the get_userdatabylogin it still worked.  So maybe something changed in wordpress (since that solution was posted 4 years ago) to make this not work.

The last problem I found was that I left two variables with the same names from the php file they were in before ($wti_like_message and $wti_unlike_message).  So I fixed this (renamed them to $like_count and $unlike_count) and now they will work again and be put into the $result array.

At the end of everything here's today's handlelikedata.php: http://pastebin.com/7fuf5R0i

So not much was accomplished today but I did once again learn the lesson that it can sometimes be better to code things from scratch so you have a complete understanding of what's going on.  Mindlessly copying and pasting things is never the answer and can cause you to waste more time in the end.  I still have to build the level system onto this and put the $author_id and sql queries I've made already to good use.  For the rest of the night though I'm just going to lurk on my usual forums.