Question

Once again I am having a problem that I do not know how to solve.

I'm trying to add a custom checkbox labeled "featured Product" to the page edit screen in wordpress. The idea is that whichever product page currently has this ticked will have its information displayed on the homepage of the site.

I am completely new to wordpress and PHP. I have only been learning PHP for the last 48 hours using "Tutsplus - PHP essentials" and obviously this site.

I have found this piece of code which I modified and added to function.php of my theme which has placed the checkbox in the page edit screen.

function register_post_assets(){
    add_meta_box('featured-product', __('Featured Product'), 'add_featured_meta_box', 'page', 'advanced', 'high');
}
add_action('admin_init', 'register_post_assets', 1);

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

There is a second piece of code that needs to be added below which I presume is to save the checkbox selection when the edit page is saved/updated.

function save_featured_meta($post_id){
    if(isset($_REQUEST['featured-product']))
        update_post_meta(esc_attr($post_id, '_featured-product', esc_attr($_REQUEST['featured-product'])); 
}
add_action('save_post', 'save_featured_meta');

However whenever I try to run the page with the second piece of code included I am informed there was an error on the line update_post_meta(esc_attr($page_id, '_featured-product', esc_attr($_REQUEST['featured-product']));

I'd appreciate it if anyone could help me figure out why this is not working, and if what I have changed is right at all.

Also what then would be the easiest/best way to echo out the title of this select page on the homepage?

Was it helpful?

Solution

Try

function save_featured_meta($post_id){
    if(isset($_REQUEST['featured-product']))
        update_post_meta( $post_id, '_featured-product', esc_attr($_REQUEST['featured-product'])); 
}
add_action('save_post', 'save_featured_meta');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top