Showing posts with label how. Show all posts
Showing posts with label how. Show all posts

Sunday, January 13, 2013

How to list archive years per category in wordpress

This post will teach you how to list down archive years per category in your wordpress site. The script below is using SQL statement that will query from your wordpress table and the tables involve are: posts, term_relationships, term_taxonomy, and terms.

"SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id AND $wpdb->term_taxonomy.taxonomy='category') INNER JOIN $wpdb->terms ON ($wpdb->terms.term_id = $wpdb->term_taxonomy.term_id) WHERE $wpdb->terms.slug='<your category slug here>' ORDER BY post_date DESC"

To get the archive years per category slug, you just need to supply it below.

.... WHERE $wpdb->terms.slug='<your category slug here>' ORDER BY post_date DESC"); 

If you want to select using your category name, then change the condition above with name field $wpdb->terms.name.

.... WHERE $wpdb->terms.name='<your category name here>' ORDER BY post_date DESC"); 

<ul>
<?php

$years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id AND $wpdb->term_taxonomy.taxonomy='category') INNER JOIN $wpdb->terms ON ($wpdb->terms.term_id = $wpdb->term_taxonomy.term_id) WHERE $wpdb->terms.slug='<your category slug here>' ORDER BY post_date DESC");               

foreach($years as $year) : ?>
        <li><a href="<?php echo get_year_link($year); ?>"><?php echo $year;?></a></li>                          
<?php endforeach; ?>

</ul> 

Please leave a comment if you like this post. Happy coding!!

Tuesday, December 20, 2011

How to put a style on input file type using CSS and jQuery

I came to this development where in I need to put a style on input file element. This is actually a challenge for me, but was able to find a way to do it. The button and inputbox is normally display in one call of an element. However, in CSS we can't style it the way we do with a normal input box, text area, etc.. and the only way for us to style it is to use jQuery/Javascript with a simple cheat using CSS.

First, we need to have a style for our inputbox and button.., that is actually for you to decide on how you want it to be.

Second, setup the HTML with the input file type element together with a styled inputbox and button. Please see below on how it will look like and take note of the id attribute I put in to be use for jQuery.

<input type="text" id="inputbox" name="inputbox" class="myinputbox"/>
<input type="button" id="button" name="button" class="mybutton"/>
<input type="file" id="inputfile" name="inputfile"/>


Once you've setup your HTML, we need to use the jQuery to trigger the #inputfile whenever we click on #inputbox or #button. Please see below.

$('#inputbox, #button').click(function() {
    $('#inputfile').trigger('click');
});


We also need to get the value of the #inputfile and change the value of the styled #inputbox as it changes. This is normally the filename of the file you selected on the open file dialog box.

$('#inputfile').change(function() {
    var data = $(this).val();
    var file = data.length ? data.split('\\').pop() : '';
    $('#inputbox').val(file);
});


Now, whenever you click on #inputbox and #button, the open file dialog box should appear and any change of value on #inputfile should reflect on #inputbox.

Lastly, we need to hide the #inputfile and retain the styled #inputbox and #button with a functional input file type element.

We can't use style="display:none" coz in some browsers JS will not work if the element is HIDE. So, the best way to do it is to set the opacity to "0" zero. This is a simple cheat to hide the elements without disabling them.

You will also have to consider other browsers, so the style should support all browsers. Please see below.

-moz-opacity:0;
filter:alpha(opacity:0);
opacity:0;


In summary, your HTML script should be like this.

<html>
<head>
<title>How to put a style on input file type using CSS and jQuery</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
    <input type="text" id="inputbox" name="inputbox" class="myinputbox"/>
    <input type="button" id="button" name="button" class="mybutton"/>
    <input type="file" id="inputfile" name="inputfile" style="opacity:0"/>
</body>
<html>
<script type="text/javascript">
$(document).ready(function() {
    $('#inputbox, #button').click(function() {
        $('#inputfile').trigger('click');
    });

    $('#inputfile').change(function() {
        var data = $(this).val();
        var file = data.length ? data.split('\\').pop() : '';
        $('#inputbox').val(file);
    });
});
</script>


Hope this helps a lot of developers.
Please see also my new post "File upload with style using jQuery and CSS".

Sunday, December 4, 2011

How to validate email address in PHP and jQuery.

PHP has a built in function where you can validate email address, but please take note that it only validates the format of the email address and not to check whether it is real or not.

To check whether the email address is real, you just have to put verification process to your application. Usually, verification process goes with registration process where user have to input their email address and other credentials. The application should send a confirmation link to the email address upon registration. The confirmation link must then be clicked by user to verify their registration or email address.

Anyway, for pre-validation, it's still better to put format validation of email address. This is for the application not to waste time of sending emails. Please see below for the quick and easy way in PHP.

<?php
$email = 'paul123@wideumbrella';

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "valid";
} else {
        echo "invalid";
}

?>


You can also validate the email address using jQuery. Please see custom function and implementation I did for jQuery.

<html>
<head>
<title>Validate Email</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
        $.fn.validateEmail = function() {
                var email = $(this).val();
                var pattern = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);

                return pattern.test(email);
        }

        $(document).ready(function() {
                $('.btnValidate').click(function() {
                        alert($('#email').validateEmail());
                });
        });
</script>
</head>
<body>
        <input type="text" value="" id="email"><a class="btnValidate" title="Validate" href="#">Validate</a>
</body>
</html>


Quote for the day: Perseverance is needed to release most of life's rewards. It's the last step in the race that counts the most. That is where the winner is determined. That is where the rewards come. If you run every step of the race well except the last one and you stop before the finish line, then the end result will be the the same if you never ran a step.

Friday, November 18, 2011

How to disable resize functionality on textarea

Textarea by default is resizable by dragging the bottom right corner of the element. Having that functionality will causes the layout to crash if we implemented styles in our textarea, such as having a background image instead of shadow style. That is because the background image doesn't follow the size of the textarea when resized.

We can disable the resize functionality by setting the resize to none. Please see below for the implementation.

<html>
<head>
<title>Disable Resize in Textarea</title>
</head>
<body>
<textarea style="resize:none" rows="5" cols="5"></textarea>
</body>
</html>

Thursday, November 17, 2011

How to show a running date and time clock in your website.

Using Ajax, I created a simple script that will show a running date and time clock in the website. Basically, the function will get the actual date and time of the server, then set a time out that loop in every second.

To get the date and time, you can initialize it by Date() object.

var today = new Date();


From there, you can get the date and time, please see below for the object methods that you can call.

var cmonth = today.getMonth(); // this will return the index of the month[0-11]
var cyear = today.getFullYear(); // this will return the year in 4 digits
var cday = today.getDate();
var chour = today.getHours();
var cmin = today.getMinutes();
var csec = today.getSeconds();


As for the complete implementation, please see below.

<html>
<head>
        <title>Hotel Aide</title>
        <script type="text/javascript">
        function updateTime() {
                var today = new Date();
                var month = new Array(12);
                month[0]="Jan";
                month[1]="Feb";
                month[2]="Mar";
                month[3]="Apr";
                month[4]="May";
                month[5]="Jun";
                month[6]="Jul";
                month[7]="Aug";
                month[8]="Sep";
                month[9]="Oct";
                month[10]="Nov";
                month[11]="Dec";

                var cmonth = month[today.getMonth()];
                var cyear = today.getFullYear();
                var cday = today.getDate();
                var chour=today.getHours();
                var cmin=today.getMinutes();
                var csec=today.getSeconds();

                if (chour<10) chour = "0"+chour;
                if (cmin<10) cmin = "0"+cmin;
                if (csec<10) csec = "0"+csec;

                document.getElementById('datetime').innerHTML= cmonth+' '+cday+', '+cyear+' '+chour+':'+cmin+':'+csec;
                window.setTimeout('updateTime();',1000);
        }
        </script>
</head>
<body onLoad="updateTime();">
        <span id="datetime"></span>
</body>
</html>


Hope this is helpful! Thanks!

Sunday, October 16, 2011

JSP 101: How to make a POST and GET method request in JSP

I would like to share with you the GET and POST method request I created while doing some JSP coding.

The example below is a GET method request that will access a specific URL passing the parameters as query string. 


<%@ page language="java" session="false"
import="java.util.*"
import="java.io.*,java.net.*"
%>

<%
try {
        String strLine = "";
        String xmlReturn = "";
       
        URL url = new URL("http://www.example.com/yourscript.jsp?param1=testparam1¶m2=testparam2");

        // read all the text returned by the server
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

        while ((strLine = in.readLine()) != null) {
            xmlReturn += strLine;
        }

        // print out xml return by the server
        out.print(xmlReturn);
        in.close();
} catch (MalformedURLException e) {
} catch (IOException e) {
}

%>


The example below is a POST method request that will access a specific URL passing the parameters in a POST manner.


<%@ page language="java" session="false"
import="java.util.*"
import="java.io.*,java.net.*"
%>

<%
try {
        String strLine = "";
        String xmlReturn = "";

        URL url = new URL("http://www.example.com/yourscript.jsp");

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
//      connection.setInstanceFollowRedirects(false);

        DataOutputStream xmlRequest = new DataOutputStream(connection.getOutputStream());
        xmlRequest.writeBytes("param1=testparam1&param2=testparam2");
        xmlRequest.flush();
        xmlRequest.close();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                // server returned HTTP 200 and response okay.

                // read all the text returned by the server
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                while ((strLine = in.readLine()) != null) {
                    xmlReturn += strLine;
                }


                // print out xml return by the server
                out.print(xmlReturn);
                in.close();
        } else {
                // server returned HTTP error code.
                out.print(connection.getResponseCode());
        }

} catch (MalformedURLException e) {
} catch (IOException e) {
}

%> 


Hope this helps you on your JSP endeavor. Happy coding!!

Quote for the day: The real heart of servanthood is security. Show me someone who thinks he is too important to serve, and I'll show you someone who is basically insecure. How we treat others is really a reflection of how we think of ourselves. - john m.

Saturday, October 15, 2011

How to align in center your modal page in jQuery

I have created a jQuery function that will align your modal page in center. The alignment will default to "0" if it encounters a negative value.

Please see below script.

$.fn.doCenter = function () {
    var topVal = (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop();
    var leftVal = (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft();

    if (topVal < 0) topVal = 0;
    if (leftVal < 0) leftVal = 0;

    this.css("position","absolute");
    this.css("top", topVal + "px");
    this.css("left", leftVal + "px");

    return this;
}


Sample usage:

$("#yourmodal").doCenter();


Give it a try, you will love it!!

Leadership 101


  • Leadership demands sacrifices for the near-term to receive lasting benefits. the longer we wait to make sacrifices, the harder they become. Successful people make important decisions early in their life, then manage those decisions the rest of their lives.
  • Growth does not happen by chance. If you want to be sure to grow, you need a plan something strategic, specific, and scheduled. it's a discipline that would need incredible determination from us.
  • Success comes by going the extra mile, working the extra hours, and investing the extra time. The same is true for us. If we want to get to excel in any segment of life, a little extra effort can help. Our efforts can go a long way if we only work a little smarter, listen a little better, push a little harder, and persevere a little longer.
  • Making a difference in your work is not about productivity; it's about people. When you focus on others and connect with them, you can work together to accomplish great things.
  • Envision a goal you'd like to reach. Make it big enough to scare you a little. Now write down a plan for moving toward it. Create mini-goals within the big goal, to set yourself up for continual progress. And include some risks, too. Set yourself up for success.
  • Leaders build margins, not image. A leader may be forced to take unpopular stands for the good of the company. Popularity isn't bad, but decisions made solely on the basis of popular opinion can be devastating. So take courage and make the right though sometimes painful choices.