Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress custom fields in custom post types

Tags:

php

wordpress

The theme I purchased came without custom fields in the post/product editor. It uses a custom post type in its own admin php file. I've managed to add custom fields by pulling the following code out of wordpress core metabox.php file however I'm unsure how to get it to work. Its missing the area where the custom field values should go.

<div id="postcustomstuff">
<div id="ajax-response"></div>
<?php
$metadata = has_meta($post->ID);
list_meta($metadata);
meta_form(); ?>
</div>
like image 634
steen Avatar asked Apr 09 '26 00:04

steen


2 Answers

The developer forgot to support "custom-fields" when calling register_post_type.

When editing a post, if there is no checkbox under screen options for Custom Fields that's why. In the init hook for my plugin I do...

register_post_type('mynamespace_product',
    array('labels' => array(
            'name' => __( 'Products' ),
            'singular_name' => __( 'Product' )
            ),
        'taxonomies' => array('category', 'product_type'), // this is IMPORTANT,                
        'public' => true,
        'has_archive' => true,
        'supports' => array('title','editor','custom-fields','comments')    
        )           
    );
like image 183
UprightNetizensBrigade Avatar answered Apr 10 '26 13:04

UprightNetizensBrigade


To get the custom fields associated to a post, you can query it this way:

 if ( get_post_meta($post->ID, 'my_customfield', true) ) : 
 echo get_post_meta($post->ID, 'my_customfield', true) 
 endif; 

Hope this helps

like image 25
Erwan Avatar answered Apr 10 '26 12:04

Erwan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!