0

How to Make Featured Post in WordPress

To Make the featured post we are adding a checkbox as a custom field add the following code to add the checkbox as a custom field
How to Make Featured Post in WordPress

[code language=”php”]

function register_post_assets(){
add_meta_box(‘featured-post’, __(‘Featured Post’), ‘add_featured_meta_box’, ‘post’, ‘advanced’, ‘high’);
}
add_action(‘admin_init’, ‘register_post_assets’, 1);

function add_featured_meta_box($post){
$featured = get_post_meta($post->ID, ‘featured-post’, true);
// echo $featured;
echo "<label for=’_featured-post’>".__(‘Feature this post?’, ‘foobar’)."</label>";?>
<input type=’checkbox’ name=’featured-post’ id=’featured-post’ value=’1′ <?php if($featured==1){echo "checked";}?>/>
<?php
}

function save_featured_meta($post_id){
// Do validation here for post_type, nonces, autosave, etc…
//print_r($_REQUEST);

if(isset($_REQUEST[‘featured-post’])){ $featuredvalue=$_REQUEST[‘featured-post’];}else{ $featuredvalue=0; }
update_post_meta($post_id, ‘featured-post’, esc_attr($featuredvalue));
// I like using _ before my custom fields, so they are only editable within my form rather than the normal custom fields UI
}
add_action(‘save_post’, ‘save_featured_meta’);

[/code]

Custom Wp-query to show the featured Post in the your template add the follwoing code

[code language=”php”]

<?php
$query_args=array(
‘post_type’=>’resource’,
‘posts_per_page’=> 1,
‘meta_query’ => array(
array(
‘key’ => ‘featured-post’,
‘value’ => 1,
‘compare’ => ‘IN’,

),
),

);
$the_query = new WP_Query($query_args);

if ($the_query->have_posts()) :
// Start the Loop.
while ($the_query->have_posts()) : $the_query->the_post();
?>

// loop Content

<?php
endwhile;

endif;
?>

[/code]

Custom wp-query to show non feature posts in you template add the follwing code

[code language=”php”]

<?php
$query_args=array(
‘post_type’=>’resource’,
‘posts_per_page’=> 1,
‘meta_query’ => array(
array(
‘key’ => ‘featured-post’,
‘value’ => 0,
‘compare’ => ‘IN’,

),
),

);
$the_query = new WP_Query($query_args);

if ($the_query->have_posts()) :
// Start the Loop.
while ($the_query->have_posts()) : $the_query->the_post();
?>

// loop Content

<?php
endwhile;

endif;
?>
[/code]

Sandeep Kumar

Sandeep kumar is a web developer and a professinal blogger. He works for latest technologies and write articles what he learn. In ICodeHub he share web languages tutorials and other programming tips and tricks. if you need some help or have some suggestion then mail him at sandeep92pal@gmail.com without any hesitation. He believes in learning and sharing.