A Sharing from Random Thoughts and Ideas

Latest

Creating Repository with Git and Dropbox

Install mysgit client

d:/original_files

1. git init

2. git add *

3. git commit -m “added initial files”

 

Create another directory for repository

4. cd d:

5. mkdir repos.git

6. git init –bare

 

Adding remote repository to clone the original files to repository

7. cd d:/original_files

8. git remote add origin d:/repos.git

9. git push origin master

 

Then the original files now has been created duplicated to the d:/repos.git (repository)

Rename directory d:/repos.git -> d:/repos

You can now clone the repository to any working directory you want to have

like  d:/working-directory
10. clone the Dropbox repository using smart git (git UI for user friendly easiness)

11. then use the stage->commit->push

for any updated files

and for getting updates from the repository

12. use pull->fetch->see changes->merge->commit->push

 

Every changes on the working directory ->when push dropbox will be updated

That’s it..

Creating Custom Widget for WordPress – Featured Post Widget

We already knew how to create WordPress Plugin based on the older posts here.

Like we have the code snippets below.

/*
Plugin Name: Featured Post
Plugin URI: http://angelohere.wordpress.com/plugin
Description: Displaying Featured Post
Version: 1.0
Author: Angelo M.
Author URI: http://angelohere.wordpress.com
License: A “Slug” license name e.g. GPL2
*/

One of the good features of wp was having some custom widget created

based on the coder.

Like for example you want to add a widget in some section of your page or posts, archive, or any templates of your site.

You will just have to drag that widget and add it on the particular sidebar container or any section container of the site

wherein you want it to show, isn’t it that simple?

But the problem is how about, if you want to add some dynamic widgets and it is not available on the widgets area.

So you have no choice instead you will look for some existing plugins that functions the same with what you want.

However the said creation of widget is just very simple to create.

So if you can carry how to do the said functionality and include it on your own custom widget and add it to the List of Widgets of WP,

just follow the simple steps here below:

1. Create A Plugin that Describes the functionality of the widget.

eg:

<?php
/*
Plugin Name: Featured Post
Plugin URI: http://angelohere.wordpress.com/plugin
Description: Displaying Featured Post
Version: 1.0
Author: Angelo M.
Author URI: http://angelohere.wordpress.com
License: A “Slug” license name e.g. GPL2
*/

?>

2. Create a class and then extends the WP widget class named ‘WP_Widget’

include its constructor method of the class

eg:

class FeaturedPost extends WP_Widget {

$widget_options = array(‘classname’ => ‘FeaturedPost’, ‘description’ => ‘Displayed Featured Posts’);
parent::__construct(false, ‘Featured Post’, $widget_options, $control_options);

}

3. Override the 3 important methods of the WP_Widget class

function widget($args, $instance) {}

function update($new_instance, $old_instance) {}

function form($instance) {}

These 3 methods must exist on your own custom widget class

*widget method – the used of this method is the one who will handle on how you are going to display the said contents of any on the pages,posts,etc. on your site the layouts or the contents on how you are going to display.

*update method – used for any updates you have in the input forms of the widget, so it is basically updating the said content, it only updates the data, no layout here.

*form method – used for any input controls you are going to add on the widget form like the Title text field, Name textfield, etc.

So assuming we have now the three methods included on our custom class widget.

We will now add the functionality code of our content widget.

/**
*
* @param type $args
* @param type $instance
*/
function widget($args, $instance) {
extract($args);
$title = $instance['title'];
$catID = $instance['feat_category'];
//for custom css of the widget contents
echo ‘<link rel=”stylesheet” media=”all” type=”text/css” href=”‘ . get_bloginfo(‘url’) .’/wp-content/plugins/featuredPost/css/style.css”/>’;
echo $before_widget;
?>
<h3><?php echo $title; ?></h3>
<?php
$this->displayFeaturedPost($catID);
echo $after_widget;
}

/**
*
* @param type $new_instance
* @param type $old_instance
* @return type
*/
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = $new_instance['title'];
$instance['feat_category'] = $new_instance['feat_category'];
return $instance;
}


/**
*
* @param type $instance
*/
function form($instance) {
?>
<p>
<label for=”<?php echo $this->get_field_id(‘title’); ?>”><?php _e(‘Title: ‘); ?></label>
<input id=”<?php echo $this->get_field_id(‘title’);?>” name=”<?php echo $this->get_field_name(‘title’); ?>” type=”text” value=”<?php echo $instance['title']; ?>” style=”width:200px”/>
</p>
<?php
$gender = $instance['gender'];
$selCategory = $instance['feat_category'];
$categories = get_categories();
?>
<p>
<label for=”<?php echo $this->get_field_id(‘gender’); ?>”><?php _e(‘Featured Category: ‘); ?></label><br/>
<select id=”<?php echo $this->get_field_id(‘feat_category’); ?>” name=”<?php echo $this->get_field_name(‘feat_category’)?>”>
<?php
foreach ($categories as $category) {
?>
<option <?php if ($selCategory == $category->cat_ID) echo ‘selected=”selected”‘;?> value=”<?php echo $category->cat_ID; ?>”>
<?php echo $category->name; ?>
</option>
<?php
}
?>
</select>
</p>
<?php
}

/**
* @author Angelo M.
* @param type $catID
* @uses for Displaying and managing thg Featured Post
*/
function displayFeaturedPost($catID) {

$args = array( ‘numberposts’=> 5,
‘offset’ => 0,
‘cat’ => $catID,
‘orderby’ => ‘post_date’,
‘order’ => ‘DESC’,
‘post_type’ => ‘post’,
‘post_status’ => ‘publish’ );

$posts = get_posts($args);
$count = count($posts);
for($i = 0; $i < $count; $i++) {
?>
<?php
if ($i != $count-1) {
?>
<div id=”home-headlines-article”>
<?php
} else {
?>
<div id=”home-headlines-article-last”>
<?php
}
$anchor = ‘<h1 id=”headlines-post-title” >’. $posts[$i]->post_title . ‘”</h1>’;
echo ‘<p>’. $anchor . ‘</p>’;
$content = $posts[$i]->post_content;
$ellipseLength = 300;
$strLen = strlen($content);
if ($ellipseLength <= $strLen)
$subContent = $this->stringEllipsis($content, $ellipseLength, ”);
else
$subContent = $this->stringEllipsis($content, $strLen, ”);
echo $subContent;
?>
<div style=”float: right;”>
<br><a style=”color: #BB0011;” href=”<?php echo get_permalink($posts[$i]->ID); ?>”>Read More&nbsp;>></a>
</div>
</div>
<?php
}
}

So that’s it.

The Featured Post Widget is now available on the list of widgets in your WP dashboard.

It’s up to you on where you will put the said Featured Post Widget in your Section Container (header, sidebar, footer, etc.)

Classes and class instance variables in Ruby

I have started learning Ruby..

Since one my colleagues had asked me if I know some great stuffs with Ruby on Rails.

So I have started learning curved in Ruby, and So I have discovered.. Very great features with Ruby.
It has really a very dynamic features. More specifically you have nothing to worry in the memory management.
It has a self contained garbage collection..moreover no declarations required.
And much more, it is really a kind of OOP of those variables.
Really all were treated as Object.

So that is why I have something to share on this simple code snippets I have created.

#sample Class Thing

class Thing

@@num_thingCounter = 0           #class variable same as of static variable
attr_reader :name             #attr_reader – it automatically creates an instance/class variable in a class
attr_reader :description
attr_writer :name             #attr_writer – it added the features for having an accessor methods automatically
attr_writer :description
attr_accessor(:name, :description)      #same with attr_writer only that it can handle many vars

def initialize (name, description)
@@num_thingCounter += 1
self.name = name
self.description = description
#or
@name = name
@description = description
end

def numthingCounter
@@num_thingCounter
end

end

#Instance of an object
thing = Thing.new(‘LLC Herbals’, ‘skin products’)
puts thing.description
thing.name = ‘LLC Supplements’
puts thing.name

puts thing.numthingCounter

thing = Thing.new(‘LLC Herbals1′, ‘skin products’)
puts thing.description
thing.name = ‘LLC Supplements1′
puts thing.name

puts thing.numthingCounter

#so that is it..as you have noticed it was really very dynamic isn’t it?..
This is something I really want..very programmer friendly.. ^^

Creating wordpress plugin (LOGIN VIEWER)

For creating wordpress plugin. I will show how to create a very simple one..

The purpose of this plugin by the way is to create a login viewer for the site created in wordpress.

Create a file then name like loginviewer.php

Insert the necessary template label for that file at the very top of the page..

/*
Plugin Name: Login Viewer
Plugin URI: http://angelohere.wordpress.com/plugin
Description: View the User login logs
Version: 1.0
Author: ngelMat
Author URI: http://angelohere.wordpress.com
License: A "Slug" license name e.g. GPL2
*/

<?php
include_once 'includes/db_setup.php';
$objLoginViewer = new LoginViewer();

function admin_init_loginviewer() {
    register_setting('loginviewer', 'log');
}

function admin_activate_loginviewer() {
    global $objLoginViewer;
    $objLoginViewer = new LoginViewer();
    $objLoginViewer->createDatabase();    
}

function admin_deactivate_loginviewer() {
    global $objLoginViewer;
    $objLoginViewer = new LoginViewer();
    $objLoginViewer->dropDatabase();    
}

function admin_menu_loginviewer() {    
    add_options_page('Login Viewer', 'Login Viewer', 'level_8', 
'loginviewer', 
'options_page_loginviewer');

}

function options_page_loginviewer() {    
    include_once WP_PLUGIN_DIR . '/loginviewer/options.php';;
}

function postUserLogged($user) {
    global $objLoginViewer;
    $objLoginViewer->postLoggedIn($user);
}

function postUserLoggedOut() {
    global $objLoginViewer;    
    date_default_timezone_set('EST');
    $dateTimeEnded = date(' Y:m:d H:i:s A ');
    $_SESSION['logout_time'] = $dateTimeEnded;
    $objLoginViewer->postLoggedOut();
}

register_activation_hook(__FILE__, 'admin_activate_loginviewer');
register_deactivation_hook(__FILE__, 'admin_deactivate_loginviewer');

if (is_admin ()) {
    add_action('admin_init', 'admin_init_loginviewer');
    add_action('admin_menu', 'admin_menu_loginviewer');
}
add_filter('wp_logout', 'postUserLoggedOut');

?>


//in options.php file
//insert this code
<div class="wrap">
<h2>Login Viewer</h2>
    <?php
        include_once 'tableData.php';
    ?>
</div>


//for the database setup 
1. create a folder named includes/ and then create a file there named
db_setup.php

<?php
//session_start();
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
class LoginViewer {

    
    var $table = 'loginlogged';
    var $user_login;
    var $user_email;



    function  __construct() {

    }

    
    function createDatabase () {
        global $table_prefix;
        global $wpdb;

        $this->dropDatabase();
        $query = "CREATE TABLE $table_prefix$this->table
                    (id BIGINT(20) NOT NULL AUTO_INCREMENT,
                    user_login VARCHAR(60) NOT NULL ,
                    user_email VARCHAR(100) NOT NULL ,
                    role VARCHAR(100) NOT NULL ,
                    user_display_name VARCHAR(250) NOT NULL ,
                    login_time DATETIME NOT NULL ,
                    logout_time DATETIME NOT NULL,
                    PRIMARY KEY (id)  );";

        dbDelta($query);

    }

    function dropDatabase() {        
        global $table_prefix;
        global $wpdb;

        $query = "DROP TABLE IF EXISTS $table_prefix$this->table; ";        
        dbDelta($query);
    }


    function postLoggedIn($user) {
        global $table_prefix;
        global $wpdb;
        
        $currentUser = $user;
        date_default_timezone_set('EST');
        $dateTimeStarted = date(' Y:m:d H:i:s A ');        

        if (isset ($currentUser)) {
            if (isset ($currentUser->user_login))
                $postUser['user_login'] = $currentUser->user_login;
            if (isset ($currentUser->user_email))
                $postUser['user_email'] = $currentUser->user_email;
            if (isset ($currentUser->display_name))
                $postUser['display_name'] = $currentUser->display_name;
            if (isset ($currentUser->roles[0]))
                $postUser['role'] = $currentUser->roles[0];
            $postUser['login_time'] = $dateTimeStarted;


        }
        $countUserField = count($postUser);                
        if ($countUserField == 5) {

            $query = "INSERT INTO $table_prefix$this->table
                                (
                                 user_login,
                                 user_email,
                                 role,
                                 user_display_name,
                                 login_time)
                    VALUES (
                            '" . $postUser['user_login'] . "',
                            '" . $postUser['user_email'] . "',
                            '" . $postUser['role'] . "',
                            '" . $postUser['display_name'] . "',
                            '" . $postUser['login_time'] . "')";
            
            $wpdb->query($query);
        }

    }

    function postLoggedOut() {
        global $table_prefix;
        global $wpdb;
        
        $currentUser = wp_get_current_user();        
        if (isset ($currentUser)) {
            if (isset ($currentUser->user_login))
                $postUser['user_login'] = $currentUser->user_login;
        }
        date_default_timezone_set('EST');
        $dateTimeEnded = date(' Y:m:d H:i:s A ');
        $postUser['logout_time'] = $dateTimeEnded;
        
        
        $loggedId = $wpdb->get_var($wpdb->prepare("SELECT ID 
FROM $table_prefix$this->table WHERE user_login = %s ORDER BY id DESC LIMIT 1" , 
$postUser['user_login']));


        $query = "UPDATE $table_prefix$this->table
                    SET logout_time = '" . $postUser['logout_time'] . "'
                    WHERE id = $loggedId ;";
        $wpdb->query($query);
        
    }


    function selectAll () {
        global $table_prefix;
        global $wpdb;

        $query = "SELECT
                      user_login,
                      user_email,
                      role,
                      user_display_name,
                      login_time,
                      logout_time
                    FROM $table_prefix$this->table
                    ORDER BY id desc;";
        $result = $wpdb->get_results($query);
        $tableName = $table_prefix . $this->table;
        if($wpdb->get_var("show tables like '$tableName'") != $tableName) {
            $this->createDatabase();
        }
        
        return $result;
    }


   
}
?>



//Then create tabledata.php file wherein it is the 
script which we will be viewing the data presentation and insert the code below.

<?php
$objLoginViewer = new LoginViewer();
$loginLogs = $objLoginViewer->selectAll();
?>
<style type="text/css">
.loginViewer-logs {
    border: 1px solid #DFDFDF;
    width: 100%;    
}
.loginViewer-logs thead,#loginViewer-logs th  {
    background: #ddd6d6;
    font-weight: bold;
}
.loginViewer-logs #odd {
    background: #fcf1f1;
}
.loginViewer-logs #even {
    background: #fff;
}
.loginViewer-logs td,
.loginViewer-logs td {
    width: 200px;
    text-align: left;
}
#login-dataTitle {    
    color: #21759B;
    text-align: left;
}
#loginlogs-data {
    max-height: 400px;
    overflow: scroll;
}

</style>
<table class="loginViewer-logs" cellspacing="0" cellpadding="2">
    <thead id="login-dataTitle">
        <td>Login Name</td>
        <td>Email</td>
        <td>Role</td>
        <td>Name</td>
        <td>Login Time</td>
        <td>Logout Time</td>
    </thead>
</table>
<div id="loginlogs-data">
<table class="loginViewer-logs">
    <tbody>
        <?php
            $row = 0;
            if (isset ($loginLogs) && count($loginLogs))
            foreach ($loginLogs as $loginLog) {
                $row++;
        ?>
            <?php
                if ($row % 2 == 1) {
            ?>
                    <tr id="odd">
                        <td><?php echo $loginLog->user_login; ?></td>
                        <td><?php echo $loginLog->user_email; ?></td>
                        <td><?php echo $loginLog->role; ?></td>
                        <td><?php echo $loginLog->user_display_name; ?></td>
                        <td><?php
                            if ($loginLog->login_time != '0000-00-00 00:00:00')
                                echo date("m/d/Y g:i:s A",
strtotime($loginLog->login_time)) ;
                            else
                                echo $loginLog->login_time;
                            ?>
                        </td>
                        <td><?php

                            if ($loginLog->logout_time != '0000-00-00 00:00:00')
                                echo date("m/d/Y g:i:s A",
strtotime($loginLog->logout_time)) ;
                            else
                                echo $loginLog->logout_time;
                            ?>
                        </td>
                    </tr>
            <?php
                } else {
            ?>
                    <tr id="even">
                        <td><?php echo $loginLog->user_login; ?></td>
                        <td><?php echo $loginLog->user_email; ?></td>
                        <td><?php echo $loginLog->role; ?></td>
                        <td><?php echo $loginLog->user_display_name; ?></td>
                        <td><?php
                            if ($loginLog->login_time != '0000-00-00 00:00:00')
                                echo date("m/d/Y g:i:s A",
strtotime($loginLog->login_time)) ;
                            else
                                echo $loginLog->login_time;
                            ?>
                        </td>
                        <td><?php

                            if ($loginLog->logout_time != '0000-00-00 00:00:00')
                                echo date("m/d/Y g:i:s A",
strtotime($loginLog->logout_time)) ;
                            else
                                echo $loginLog->logout_time;
                            ?>
                        </td>

                    </tr>
        <?php
                }
        }
        ?>
    </tbody>
</table>
</div>


//And then lastly create a readme.txt file and put some text 
like this one in order to use this kind of loginviewer login plugin

Login viewer

insert this code in the wp-login.php
before redirection..

 if (function_exists('postUserLogged')) {
                    postUserLogged($user);
                }



//And so that is it.
We have created a plugin in order to view login logs of a wordpress site.
Hope this helps to track administration of some changes in the site..

Thanks.

Hiding Affiliate Links

Create a file something like getAffiliateLink.php

And

Include this file to where you want see these link/s

<?php

$baseUrl = ‘http://’ . $_SERVER['HTTP_HOST'];
$requestURI = $_SERVER['REQUEST_URI'] . ‘webpage1/prod1′;
$requestURI = str_replace(‘tut6/’, ”, $requestURI);
$affiliateLink = $baseUrl . ‘/tut6/products/sample’ . $requestURI;
?>

<a href=”<?php echo $affiliateLink; ?>”>Affiliate</a>
and create .htaccess
and add these scripts below:
RewriteEngine On
#example site is http://www.google.com
RewriteRule ^products/sample/?$ http://www.google.com/affiliation-$1/?%{QUERY_STRING} [R=302,L]
RewriteRule ^products/sample/?$ http://www.google.com/affiliation/?%{QUERY_STRING} [R=302,L]
RewriteRule ^products/sample/([a-zA-Z0-9]+)/?$ http://www.google.com/affiliation-$1/?%{QUERY_STRING} [R=302,L]
RewriteRule ^products/sample/([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/?$ http://www.google.com/affiliation-$1/$2%{QUERY_STRING} [R=302,L]

 

//end
Then that’s it… ^^

Detect User browser

 

<?php

//some codes here;

add_filter(‘body_class’,'browser_body_class’);

function browser_body_class($classes) {

global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;

if($is_lynx) $classes[] = ‘lynx’;

elseif($is_gecko) $classes[] = ‘gecko’;

elseif($is_opera) $classes[] = ‘opera’;

elseif($is_NS4) $classes[] = ‘ns4′;

elseif($is_safari) $classes[] = ‘safari’;

elseif($is_chrome) $classes[] = ‘chrome’;

elseif($is_IE) $classes[] = ‘ie’;

else $classes[] = ‘unknown’;

if($is_iphone) $classes[] = ‘iphone’;

return $classes;

}

?>

 

Display Keywords From Google Users

<?php
$refer = $_SERVER["HTTP_REFERER"];
if (strpos($refer, "google")) {
$refer_string = parse_url($refer, PHP_URL_QUERY);
parse_str($refer_string, $vars);
$search_terms = $vars['q'];
echo 'Welcome Google visitor! You searched for the following terms to get here: ';
echo $search_terms;
};
?>

Formatting date

<?php
if ($loginLog->login_time != ’0000-00-00 00:00:00′)
echo date(“m/d/Y g:i:s A”,strtotime($loginLog->login_time)) ;
else
echo $loginLog->login_time;
?>

We can simple add custom fonts in css

through giving the source file of the font

 

eg:

@font-face {
	font-family: custom-font;  
	src: local('custom-font'), 
		url("fonts/custom-font.ttf") format('truetype');  
	font-weight: normal;  
}


.post-item {font-family: custom-font

 

 

That’s it.

Adding short code

Short code is very easy to implement in wordpress without installing any plugin to your site.

Just add function to the functions.php
and then use the short code.

eg:

function getDateNow() {
date_default_timezone_set(‘EST’);
return date(‘ F d, Y’);
}

add_shortcode(‘getDateNow’, ‘getDateNow’);

and then use the shortcode to any of the site, page, post, widgets.

eg:
[getDateNow]

That’s it.

Follow

Get every new post delivered to your Inbox.