[WordPress] How to Fill Custom Field with Meta Box Interface

customfield-meta-box

WordPress is amazing CMS which you can customize it as you want, depend on your needed and creativity. WordPress have a feature called custom field, where with custom field, you can add and enhancing blog post. So, wordpress is very flexible.

But custom field interface in wordpress admin is not easy for newbie or for non-tech guys. So, many wordpress theme developer using custom field combine it with meta box. What is metabox and what difference with custom fields, you can follow that link. But, meta box makes user easily when fill custom fields.

Ok, this post will explain how to fill custom fields through meta box interface, so its easy and fast. I have modified of wordpress snippet code,

<?php
// Little function to return a custom field value
function toko_get_custom_field( $value ) {
	global $post;

    $custom_field = get_post_meta( $post->ID, $value, true );
    if ( !empty( $custom_field ) )
	    return is_array( $custom_field ) ? stripslashes_deep( $custom_field ) : stripslashes( wp_kses_decode_entities( $custom_field ) );

    return false;
}

// Register the Metabox
function create_meta_box() {
	add_meta_box( 'meta-box', __( 'Title of Metabox', 'textdomain' ), 'process_meta_box', 'post', 'normal', 'high' );
}
add_action( 'add_meta_boxes', 'create_meta_box' );

// Output the Metabox
function process_meta_box( $post ) {
	// create a nonce field
	wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' ); ?>
	
	<p>
		<label><?php _e( 'Harga Mahal', 'textdomain' ); ?>:</label>
		<input type="text" name="harga"  value="<?php echo get_custom_fields_content( 'harga' ); ?>" size="50" />
    </p>
	
	<p>
		<label ><?php _e( 'Harga Murah', 'textdomain' ); ?>:</label>
		<input type="text" name="hargamahal"  value="<?php echo get_custom_fields_content( 'harga_mahal' ); ?>" size="50" />
    </p>
	
	
	<p>
		<label ><?php _e( 'Kode Cincin', 'textdomain' ); ?>:</label>
		<input type="text" name="kode"  value="<?php echo get_custom_fields_content( 'kode' ); ?>" size="50" />
    </p>
	
	<p>
		<label ><?php _e( 'Rating', 'textdomain' ); ?>:</label>
		<input type="text" name="rating"  value="<?php echo get_custom_fields_content( 'rating' ); ?>" size="50" />
    </p>
	

    
	<?php
}

// Save the Metabox values
function toko_meta_box_save( $post_id ) {
	// Stop the script when doing autosave
	if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

	// Verify the nonce. If insn't there, stop the script
	if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;

	// Stop the script if the user does not have edit permissions
	if( !current_user_can( 'edit_post' ) ) return;

    // Save the textfield
	if( isset( $_POST['harga'] ) )
		update_post_meta( $post_id, 'harga', esc_attr( $_POST['harga'] ) );
		
	if( isset( $_POST['hargamahal'] ) )
		update_post_meta( $post_id, 'harga_mahal', esc_attr( $_POST['hargamahal'] ) );
		
	if( isset( $_POST['kode'] ) )
		update_post_meta( $post_id, 'kode', esc_attr( $_POST['kode'] ) );
		
	if( isset( $_POST['rating'] ) )
		update_post_meta( $post_id, 'rating', esc_attr( $_POST['rating'] ) );

}
add_action( 'save_post', 'toko_meta_box_save' );
?>

Those code support for 4 custom field with key : harga, harga_mahal, kode and rating. Its my code for my online shop, but you can use it and modify it as you want.

How to Use Those Code?

Just paste it on functions.php file and you’re done.

I was looking for how to easily and fast to build meta box, but i found confused tutorial and libary. Even, you can use plugin, but its not meet my needed. And this snippet is small and useful, and work for me.

Bonus

As bonus, i am listed many resource for meta box. You can learn more and making your theme is powerful.

  1. How to Create Custom WordPress Write/Meta Boxes (codetuts)
  2. Custom Metaboxes and Fields (CMB) Library
  3. Plugin CMB2 on WordPress
  4. How to Add Custom Meta Boxes in WordPress Posts and Post Types

And, this video on youtube

New Jquery Snippet Code for Designer and Developer

Jquery is most javascript framework used by developer and designer in the world. Jquery is very important to all web development and design. Its would be basic, fondation of web app, mobile app and more.

This is my jquery snippet collection that help me alot when coding jquery. Maybe its also help you.

1. Loading Image Faster with Jquery

$.preloadImages = function() {
       for(var i = 0; i<arguments.length; i++) {
               $("<img />").attr("src", arguments[i]);
       }
}

$(document).ready(function() {
       $.preloadImages("hoverimage1.jpg","hoverimage2.jpg");
});

Its script will loading image first, the loading the page. The concept is simple, but its work.
Source

2. Image Resizing with Jquery

$(window).bind("load", function() {
	// IMAGE RESIZE
	$('#product_cat_list img').each(function() {
		var maxWidth = 120;
		var maxHeight = 120;
		var ratio = 0;
		var width = $(this).width();
		var height = $(this).height();
	
		if(width > maxWidth){
			ratio = maxWidth / width;
			$(this).css("width", maxWidth);
			$(this).css("height", height * ratio);
			height = height * ratio;
		}
		var width = $(this).width();
		var height = $(this).height();
		if(height > maxHeight){
			ratio = maxHeight / height;
			$(this).css("height", maxHeight);
			$(this).css("width", width * ratio);
			width = width * ratio;
		}
	});
	//$("#contentpage img").show();
	// IMAGE RESIZE
});

Its script will resizing image on the client side. Although, you better resizing image on the server side, in order client can be faster download.
Source

3. Select Conditional Jquery in Header

<!--[if lt IE 9]>
<script src="jquery-1.10.1.js" type="text/javascript"></script>
<![endif]-->
<!--[if gte IE 9]><!-->
<script src="jquery-2.0.2.js" type="text/javascript"></script>
<!--<![endif]-->

Source

4. Find All Internal Link with Jquery

var siteURL = "http://" + top.location.host.toString();

var $internalLinks = $("a[href^='"
         + siteURL
         + "'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']");

Its script will parse and find internal link on a page with jquery. Simple and without plugin.
Source

5. Controlling Checkbox via Jquery

    // Check if Checkbox is checked:
    $('#checkboxfield').is(':checked')
     
    // check / uncheck the checkbox
    $('#checkboxfield').prop('checked', true);
     
    // do not use attr() !
    // since jquery 1.5 prop is available, attr() has flaws

Checked or uncheck checkbox element with jquery.
Source

6. Smoth Scrolling with Jquery

$('a').click(function(){
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});

Source

7. Force input 0-9 with Jquery

    $('.class').keypress(function (key) {
    if (key.charCode < 48 || key.charCode > 57) {
    return false;
    }
    });

Source

8. Manage Cookie with Jquery

// writing coookie
$.cookie('name', 'value', { expires: 7 });
$.cookie('name', 'value', { expires: 7, path: '/' });

// read cookie
$.cookie('name'); // => "value"

//remove cookie
$.removeCookie('name'); // => true

How to Add Custom Class in Iframe When Embeding Youtube Video

When wordpress deal with Youtube, you can easily to add a youtube video, just paste youtube url video and wordpress will working to show the video in wordpress editor. This is feature on wordpress 4.0, everyone are waiting this feature come true. And right now, you can try it.

The problem is, when you want to add custom class to iframe or embeded code automaticly, how to do that?

I just search the solution in the internet and i was found best solution for it.  Just add this code to your functions.php file

add_filter( 'embed_oembed_html', 'custom_youtube_oembed' );
function custom_youtube_oembed( $code ){
    if( stripos( $code, 'youtube.com' ) !== FALSE && stripos( $code, 'iframe' ) !== FALSE )
        $code = str_replace( '<iframe', '<iframe class="add your custom class here"  ', $code );

    return $code;
}

Its code will wordpress ability to detect it is a youtube link  or not, if yes, then add custom class. Just replace add your custom class here  with your class. Done, just try it.

 

Using Regular Expression to Get Image URL in WordPress Post

Before using this tips, i used regular expression to show first image in a wordpress post. And now, i want to share simple snippet code to showing first image, of course using regular expression. This function will return image URL, so you can flexiblity to use it for any purpose. Your creativity is limit.

Put this function into your functions.php file and you be ready to use in all your template.

function get_img_url() {
  global $post, $posts;
  $first_img = '';
  ob_start();
  ob_end_clean();
  $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
  $first_img = $matches [1] [0];

  if(empty($first_img)){ 
  	$img_dir = get_template_directory_uri();
    $first_img = $img_dir . '/images/thumb.gif';
  }
  return $first_img;
}

You can use its function in Loop, i think its will be great.

if this snippet is usefull, just share with your friend in social network. Thanks for visiting, hope it help you

Snippet : How to Build Better URL CakePHP Pagination Just Like on WordPress

pagination on cakephp

Here is best cakephp snippet to build and rewrite pagination URL. You can build url like this (such as wordpress pagination)

example.com/page/1

example.com/page/2

example.com/page/3

Here is the superb snippet for it

Add this on AppController.php

function beforeFilter(){
		if (isset($this->request->params['page'])) {
			$this->request->params['named']['page'] = $this->request->params['page'];
		}
	}

Add this code to route.php

Router::connect('/page/:page', 
    array('controller' => 'controller', 'action' => 'index'),
    array(
        'pass' => 'page',
        'page' => '[0-9]+'
        )
	);

Easy for Newbie to Creating Gradient Text with CSS3

gradient text effect

CSS3 allows effects on text and other elements. However, CSS3 is also to be supported by modern browsers that have CSS3 support 100%. Some of the effects that can be used in the text one of which was: gradient. This time we will present a tutorial how to create a gradient effect on a text.

This effect is suitable for a website headline or title of an article. The impression of this effect is more cheerful, not monotonous and relax. The combination of gradient colors will create a feeling softer.

<html>
<head>
<style type="text/css">
div#header{
  position: absolute;
top: 20px;
left: 128px;
width: 640px;
height: 45px;
font-family: "Times New Roman", Times, serif;
font-weight:700;
font-size: 35px;
display: block;
 background-image: -webkit-linear-gradient(#314A23, #828C68);
 -webkit-background-clip: text;
 -webkit-text-fill-color: transparent;
position:relative; 
text-shadow: 3px 3px 5px #A7B485;
border:solid 1px color:#FFFFFF;
 }
}

</style>
</head>
<body>
<div id="header">Text will show in gradient effect</div>
</body>
</html>

That’s all it takes to create a text with a gradient effect. It’s easy right?  Good luck

[Solved] Change The Default Font Size in WP Editor

change font editor in wordpress
If the font size in wordpress editor is small enough for you, perhaps it is time to enlarge the font sizeFor an author and blogger, convenience when writing is the important thing. And perhaps, inspirationwill come when convenient to write.

Moreover, if and write using a mini laptop, 10 inch screen and low resolution. Of course this is not comfortable for the eyes.
Read more

Adding Custom Class When Upload or Insert Image in WordPress

insert class wordpress
If you used a bootstrap to build a wordpress template, you might encounter this issue. How to automatically insert custom class when uploading an image, this also applieswhen inserting images, e.g. images from other web (via URL)
In the bootstrap, so that the image looks responsive, it needs a class imgresponsive.Read the explanation here.
This time there was a snippet to make that a reality, without having to insert the class manually. The code as below

Read more

[Snippet] Generate Random String with Javascript

When creating a program, sometimes we need a useful random string to create a unique invoice, but we do not have to create it manually. The easiest and most appropriate way is to submit the task to the program we are designing.

random string

One way is with a random string. That is a special function that produces a random string, which is unique and automatically. Since I use javascript, then I use this function to generate a random string.

function makeid(){
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 5; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

This function will generate a random string of 5 characters. Quite easy right?

Tutorial Creating 100% Pure CSS Contents Slider

free font collection for designer

Slider is a good way to display some content in a confined area. There are various ways to create content slider. Content slider can be filled with images and text. Typically, the slider for the latest news, latest posts or featured posts.

In this post, I want show you some tutorials and code to create content slider. But, I do not use javascript, everything is 100% CSS code. Pure CSS, as I have previously made, with pure CSS dropdown menus.

Sometimes interfere with the use of javascript on the client side or weight. Or if the client does not support javascript, this course will create problems for us as developers. The solution is pure CSS, this is challenge me  how to make something with 100% pure CSS.

Ok, prepare your favorite editor, I usually use notepad++  Read more

Tutorial Creating Parallax Effects on Scrolling with Very Simple (Example)

parallax

Parallax be one CSS trend in 2014. Parallax is a beautiful effect when changing (scrolling) element/page. You will not know until you see the effect. Parallax will create a web page into a 3D, although not 100% looks 3D, but it gives a fresh effect.

Parallax effect made ​​with CSS and a little Javascript + HTML5, and of course, 100% responsive. You can create a lot of things with the parallax effect, this post will give you a simple example of parallax effects.

Parallax effect depends on the browser, it is undeniable that the parallax effect only works in modern browsers, but do not worry, the current Internet users use a modern browser, such as Chrome version 28 and above, Firefox newest and latest IE. Read more

Most Useful Snippet Code to Design WP Theme

using custom font with css

As a novice designer of wordpress theme ( wp theme ), I put together some functions that are widely used. I am making this post to make it easier for me when looking for a function that I need. Honestly, I do not remember with all the functions in wordpress and parameters must be entered. Because indeed, number of function in wordpress is very much, it is not easy to memorize. I’m still looking for the right book to learn wordpress.

I regret, why I am late to learn how to create a wordpress theme ( wp theme ), but I and the potential of this field. I can work more with wp theme.

This set of code snippets I collected in a few days, and will update when I get a new snippet and most often used in the design wp theme. Initially I used a program to store code snippets, but I think it is not useful, when I am away from the computer, for example when in the office.  Then I decided to collect them in a blog post.

And this is, Useful snippet code to design wp theme

Read more