I'm following a guide at the moment and have managed to create a custom post type and meta boxes. However, getting the meta data to display in a post just isn't happening for me at the moment.
All i want is the meta box to have 3 custom text fields that I can then output in a post.
This is my functions file (the part that defines the post type and meta boxes):
add_action('init', 'product_manager_register'); // Calls function to set up post-type
function product_manager_register() {
$args = array(
'label' => __('Product Manager'),
'singular_label' => __('Skin'),
'public' => true,
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => true,
'has_archive' => true,
'supports' => array('title', 'editor', 'thumbnail'),
'rewrite' => array('slug' => 'skins', 'with_front' => false),
);
register_post_type('products' , $args ); // runs the function
}
//Add featured image support to the theme
if (function_exists('add_theme_support')) {
add_theme_support('post-thumbnails');
}
add_action("admin_init", "product_manager_add_meta");
function product_manager_add_meta(){
add_meta_box("product-meta", "Product Options", "product_manager_meta_options", "products", "normal", "high");
}
function product_manager_meta_options(){
global $post;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post_id;
$custom = get_post_custom($post->ID);
$buylink = $custom['buylink'][0];
$price = $custom['price'][0];
$previewlink = $custom['previewlink'][0];
?>
<style type="text/css">
<?php include('productmeta.css'); ?>
</style>
<div class="product_extras">
<div> <label> Buy Link: </label> <input name="buylink" value="<?php echo $buylink; ?>" /></div>
<div> <label> Price: </label> <input name="price" value="<?php echo $price; ?>" /></div>
<div> <label> Preview Link: <input name="previewlink" value="<?php echo $previewlink; ?>" /></div>
</div>
<?php
}
add_action('save_post', 'save_product_meta');
function save_product_meta(){
global $post;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
return $post_id;
}else{
update_post_meta($post->ID, "buylink", $_POST["buylink"]);
update_post_meta($post->ID, "price", $_POST["price"]);
update_post_meta($post->ID, "previewlink", $_POST["previewlink"]);
}
}
?>
And I display the information in single-products like this:
<?php get_header() ?>
<div class="container content"><!-- Begin maincontent Container -->
this is the page i'm editing
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php
$custom = get_post_custom($post->ID);
$buynowlink = $custom ["buynowlink"][0];
$price = $custom ["price"][0];
$previewlink = $custom ["previewlink"][0];
?>
<div class="post group">
<h2><?php the_title(); ?> </h2>
<?php the_content(); ?>
<?php print "<p>$buynowlink</p>"; ?>
<?php print "<p>$price/p>"; ?>
<?php print "<p>$buynowlink</p>"; ?>
</div>
<?php endwhile; else: ?>
<?php endif; ?>
I know I'm probably doing something stupid but any help would be really appreciated. I know I could do this with a plugin but I'd rather learn to do it the proper way.
You just have the wrong ID's in place
so to output correctly its should be:
<?php
$custom = get_post_custom($post->ID);
$buynowlink = $custom ["buylink"][0];
$price = $custom ["price"][0];
$previewlink = $custom ["previewlink"][0];
?>
and to print it - you have the buy link in the previews rule as well as an open p tag so it should be:
<?php print "<p>$buynowlink</p>"; ?>
<?php print "<p>$price</p>"; ?>
<?php print "<p>$previewlink</p>"; ?>
Hope this helps
I think I see a couple of syntax errors in your code, such as the way you want to print the custom field's values and so on.
I would recommend this approach as opposed to the approach you are using, and I'll explain why in a bit, after the code.
PHP WordPress Loop with get_post_meta();
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<!--This is a conditional statement to see if the value of the custom field has something, and if it does then it shows it, otherwise it doesn't render anything-->
<?php if ( get_post_meta($post->ID, 'cf-size', true)):?>
<h1>Custom Field Value: <?php echo get_post_meta($post->ID, 'cf-size', true);?></h1>
<?php endif;?>
<?php endwhile; endif; ?>
You can notice that cf-size is the name of the custom field and that I'm checking for it's value on the current post. The code above will surely work as I've used it many times in my own creations.
Here is an example of how to pull 3 fields with the same if statement... just remember that if the condition doesn't validate as "true" (meaning that all 3 fields have a value) then none will show even if 2 or 1 does have a value.
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<!--This is a conditional statement to see if the value of the custom field has something, and if it does then it shows it, otherwise it doesn't render anything-->
<?php if ( get_post_meta($post->ID, 'cf-size', 'cf-color', 'cf-brand', true)):?>
<h1>Custom Field Value for Size: <?php echo get_post_meta($post->ID, 'cf-size', true);?></h1>
<h1>Custom Field Value for Color: <?php echo get_post_meta($post->ID, 'cf-color', true);?></h1>
<h1>Custom Field Value for Brand: <?php echo get_post_meta($post->ID, 'cf-brand', true);?></h1>
<?php endif;?>
<?php endwhile; endif; ?>
Related
I have created a custom post type within WordPress, and for that custom post type I have custom meta boxes where I can input the price of a product rental either per day or per week (there are 2 meta boxes).
I want to display these prices on the page that displays all the posts from my custom post type. My theme has an action hook just after the title of the post which is where I want to display the meta info.
I have managed to hook into the action, however, my information only shows on the first post, not on all of them.
Here is the code I am using to echo out the meta info:
function add_prices_to_products() {
global $post;
$price_per_day = get_post_meta($post->ID, "_per_day", true);
$price_per_week = get_post_meta($post->ID, "_per_week", true);
echo '<span class="sl_product_price per_day">£' . $price_per_day . '/day</span>';
echo '<span class="sl_product_price per_week">£' . $price_per_week . '/wk</span>';
}
add_action('layers_after_list_post_title', 'add_prices_to_products');
Can anyone tell me why it is just adding to the first post and not to all of them (I can confirm that the meta info is saving correctly)?
Here is the code of the page from the theme (index.php):
<?php get_header(); ?>
<div class="container content-main archive clearfix">
<?php get_sidebar( 'left' ); ?>
<?php if( have_posts() ) : ?>
<div <?php layers_center_column_class(); ?>>
<?php while( have_posts() ) : the_post(); ?>
<?php get_template_part( 'partials/content' , 'list' ); ?>
<?php endwhile; // while has_post(); ?>
<?php the_posts_pagination(); ?>
</div>
<?php endif; // if has_post() ?>
<?php get_sidebar( 'right' ); ?>
</div>
<?php get_footer();
it references the file content-list.php which is what contains the hook.
global $post, $layers_post_meta_to_display; ?>
<article id="post-<?php the_ID(); ?>" <?php post_class( 'push-bottom-large' ); ?>>
<?php do_action('layers_before_list_post_title'); ?>
<header class="section-title large">
<?php do_action('layers_before_list_title'); ?>
<h1 class="heading"><?php the_title(); ?></h1>
<?php do_action('layers_after_list_title'); ?>
</header>
<?php do_action('layers_after_list_post_title'); ?>
<?php /**
* Display the Featured Thumbnail
*/
echo layers_post_featured_media( array( 'postid' => get_the_ID(), 'wrap_class' => 'thumbnail push-bottom', 'size' => 'large' ) ); ?>
<?php if( '' != get_the_excerpt() || '' != get_the_content() ) { ?>
<?php do_action('layers_before_list_post_content'); ?>
<?php do_action('layers_list_post_content'); ?>
<?php do_action('layers_after_list_post_content'); ?>
<?php } ?>
<?php do_action('layers_before_list_post_meta'); ?>
<?php /**
* Display the Post Meta
*/
layers_post_meta( get_the_ID(), NULL, 'footer', 'meta-info push-bottom' ); ?>
<?php do_action('layers_after_list_post_meta'); ?>
<?php do_action('layers_before_list_read_more'); ?>
<?php do_action('layers_list_read_more'); ?>
<?php do_action('layers_after_list_read_more'); ?>
</article>
It's also worth mentioning that I am hooking in from a plugin
UPDATE
Using the hook "the_post" I am able to echo out plain text on each post in the list, however, I can't get my meta box info to echo yet. Here is what I'm using now:
add_action( 'the_post', 'my_custom_loop_start' );
function my_custom_loop_start( $query )
{
echo 'hello';
add_action( 'loop_end', 'my_custom_loop_end' );
}
function my_custom_loop_end()
{
remove_action( 'layers_after_list_post_title', 'add_prices_to_products' );
}
You need to hook into each item in the loop, try something like this...
// Hook into the main loop
add_action( 'loop_start', 'my_custom_loop_start' );
// Add two filters in that loop - your existing function and one to clear it out
function my_custom_loop_start( $query )
{
if( $query->is_main_query() )
{
add_filter( 'layers_after_list_post_title', 'add_prices_to_products' );
add_action( 'loop_end', 'my_custom_loop_end' );
}
}
// This will just remove your action once each loop is done so you get the correct data for each loop
function my_custom_loop_end()
{
remove_action( 'layers_after_list_post_title', 'add_prices_to_products' );
}
You may need to tweak this to work properly, but the logic is adding your function to each loop, running it, then removing it.
Trying to create a Featured Posts Section on my site and there are three files involved:
header file
footer file
functions file
index file
I want to make selecting a featured post is just by checking a checkbox in edit screen (posts page) AND be able to retrieve these featured articles on the front page.
So far with my current code it is showing up a checkbox only on the posts page edit screen however it won't save and on the front page nothing is appearing except the posts loop.
here's my functions.php file:
/**
* ----------------------------------------------------------------------------------------
* 1.0 - Define constants.
* ----------------------------------------------------------------------------------------
*/
define( 'THEMEROOT', get_stylesheet_directory_uri() );
define( 'IMAGES', THEMEROOT. '/images' );
define( 'SCRIPTS', THEMEROOT. '/js' );
/** */
/***********************************************************************************************/
/* 2.0 - Add Theme Support for Post Thumbnails */
/***********************************************************************************************/
if (function_exists('add_theme_support')) {
add_theme_support('post-thumbnails');
set_post_thumbnail_size(300, 200);
}
/***********************************************************************************************/
/* 3.0 - Add Theme Support for Post Thumbnails */
/***********************************************************************************************/
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 "<label for='_featured-post'>".__('Feature this post?', 'foobar')."</label>";
echo "<input type='checkbox' name='_featured-post' id='featured-post' value='1' ".checked(1, $featured)." />";
}
function save_featured_meta($post_id){
// Do validation here for post_type, nonces, autosave, etc...
if (isset($_REQUEST['featured-post']))
update_post_meta(esc_attr($post_id, '_featured-post', esc_attr($_REQUEST['featured-post'])));
// 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');
?>
Here's my code on the index.php file:
<?php get_header(); ?>
<?php while(have_posts()) : the_post(); ?>
<h1><a href="<?php the_permalink(); ?>" class="gray">
<?php the_title(); ?>
</a></h1>
<p class="details">By <?php the_author(); ?> / On <?php echo get_the_date('F j, Y'); ?> / In <?php the_category(', '); ?></p>
<?php if (has_post_thumbnail()) : ?>
<figure> <?php the_post_thumbnail('', array('class' => 'opacity-hover box-layer img-responsive')); ?> </figure>
<p class="excerpt"> <?php the_excerpt(); ?> </p>
<div class="btn-margin"> CONTINUE READING >>> </div>
</li>
<?php endif; ?>
<?php endwhile; ?>
<h1>Featured Posts</h1>
<?php
$args = array(
'posts_per_page' => 5,
'meta_key' => '_featured-post',
'meta_value' => 1
);
$featured = new WP_Query($args);
if ($featured->have_posts()): while($featured->have_posts()): $featured->the_post();
the_title();
the_content();
endwhile; else:
endif;
?>
<?php get_footer(); ?>
Any idea what's causing the problem or if I am missing something? I just want to have a featured posts section on my blog atleast similar to this image:
http://goo.gl/E5tbMv
Any help?
function add_featured_meta_box($post){
$featured = get_post_meta($post->ID, '_featured-post', true);
echo "<label for='_featured-post'>".__('Feature this post?', 'foobar')."</label>";
echo "<input type='checkbox' name='featured-post' id='featured-post' value='1' ".checked(1, $featured)." />";
}
function save_featured_meta($post_id){
// Do validation here for post_type, nonces, autosave, etc...
if (isset($_REQUEST['featured-post']))
update_post_meta(esc_attr($post_id), '_featured-post', esc_attr($_REQUEST['featured-post']));
// 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');
Try with that code, I corrected the nameattribute and the update_post_meta function. Sorry but I currently don't have a Wordpress install to try it.
You seem to use the id featured-post twice, too. You should change the id of the înput field.
I'm trying to add metabox with date in Wordpress. I used code from this page. It works well, but I have a problem displaying the metabox values on page.
My loop:
<?php query_posts(array('post_type' => 'event' , 'posts_per_page' => 9999, 'orderby' => 'menu_order', 'order' => 'ASC' ));
if (have_posts()) : while (have_posts()) : the_post();
$custom = get_post_custom($post->ID); ?>
<div class="event">
<h2><?php the_title(); ?></h2>
<p>Date: <?php echo get_post_meta($post->ID, '_day', true);?>.<?php echo get_post_meta($post->ID, '_month', true);?>.<?php echo get_post_meta($post->ID, '_year', true);?></p>
<p>Hour: <?php echo get_post_meta($post->ID, '_hour', true);?>:<?php echo get_post_meta($post->ID, '_minute', true);?></p>
<?php the_content(''); ?>
</div>
<?php endwhile; endif; ?>
I added custom post type 'event'. Values in metabox(date/location) have been saved, but it haven't displayed on page.
Why it doesn't work?
Problem solved. I have written incorrect meta_key.
For example:
Instead '_day' must be '_start_day' (for Start day) or '_end_day' (for End day)
Correct code for display metabox with Start Day:
<?php echo get_post_meta($post->ID, '_start_day', true);?>
I'm having hard time with this problems since I cant figure it out.
I'm using 2 WP_Query loops for custom post types (slider and portfolio) on the same page.
I also created a custom meta box for both custom post types.
So here is the code for index.php which Im using as Home template for displaying slider and portfolio items:
<?php
/*
Template Name: Home
*/
?>
<?php get_header(); ?>
<div id="header-container">
<div id="header">
<?php rm_slider(); ?> // This is where Im calling slider function to display the slider.
</div>
</div>
<div id="content">
<div class="container">
<?php $loop = new WP_Query(
array(
'post_type' => 'portfolio',
'posts_per_page' => -1
));
?>
<?php if ($loop->have_posts()) { ?>
<ul class="services">
<?php while ($loop->have_posts()) : $loop->the_post(); ?>
<li>
<?php if (has_post_thumbnail()) : the_post_thumbnail(); ?>
<?php else: ?>
<p>No portfolio image</p>
<?php endif; ?>
<h3><?php the_title(); ?></h3>
<p>Client: <?php echo get_post_meta($post->ID, '_project_client', true); ?></p>
<p>Client website: <?php echo get_post_meta($post->ID, '_project_client_url', true); ?></p>
</li>
<?php endwhile; } ?>
<?php wp_reset_query(); ?>
<?php get_footer(); ?>
And here is the code for slider.php:
<?php
// create slider markup
function rm_slider() {
$slider_loop = new WP_Query(
array(
'post_type' => 'slider',
'posts_per_page' => -1
));
if ($slider_loop->have_posts()) { ?>
<div id="slider">
<div class="slider-container">
<?php while ($slider_loop->have_posts()) : $slider_loop->the_post(); ?>
<div>
<?php if (has_post_thumbnail()) : the_post_thumbnail(); ?>
<?php else: ?>
<p>No slider image</p>
<?php endif; ?>
<div class="slide-info">
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
</div>
<?php
$slide_url = get_post_meta($post->ID, '_slide_url', true);
if ($slide_url != '') { ?>
<?php echo $slide_url; ?>
<?php } else { echo 'empty?'; ?>
<?php
}
?>
</div>
<?php endwhile; ?>
</div><!-- .slider-container -->
</div><!-- #slider -->
<?php }
wp_reset_query();
}
?>
Im sure that the actual content from custom meta boxes is there, because when I only use 1 loop, it displays perfectly. But when using both loops, it only displays custom post meta only for the portfolio section. Im struggling with this problem whole day, please help me! Thanks :)
Strange, try changing this:
$slide_url = get_post_meta($post->ID, '_slide_url', true);
echo get_post_meta($post->ID, '_project_client', true);
for this:
$slide_url = get_post_meta(get_the_ID(), '_slide_url', true);
echo get_post_meta(get_the_ID(), '_project_client', true);
You could also try getting all post meta just to see if its all there.
$meta = get_post_meta( get_the_ID( ) );
print_r($meta); // prints the meta array to the screen, check your data is there.
As far as I know, after every WP_Query() you should use:
wp_reset_postdata();
NOT wp_reset_query();. Have a try with this.
wp_reset_query() restores the $wp_query and global post data to the original main query. This function should be called after query_posts(), if you must use that function. As noted in the examples below, it's heavily encouraged to use the pre_get_posts filter to alter query parameters before the query is made.
and
wp_reset_postdata() is used to restore the global $post variable of the main query loop after a secondary query loop using new WP_Query. It restores the $post variable to the current post in the main query.
And I also suggest you to try changing the possible redundant variable name like $loop to something like $portfoliowLoop etc.
I have created a custom post type called "box-img."
I have to custom fields in it, one called "img-url" and "img."
The "img" fields contains an image.
I want to be able to display those 2 fields on my page. Right now I have:
<?php
global $wp_query;
query_posts(array(
'post_type' => 'box-img',
'showposts' => 4
) );
?>
<?php while (have_posts()) : the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php $key = get_post_meta($post->ID, 'img-url'); ?>
<p><?php if($key) { echo $key[0]; } else { the_title(); }; ?></p>
<?php $key1 = get_post_meta($post->ID, 'img-url'); ?>
<p> <?php echo $key1; ?> </p>
<?php endwhile;
wp_reset_query(); ?>
I have tried those 3 different ways to see what I get, but all I can get is the title to show!
Any help would be very helpful!
Thanks!
Set the third optional parameter to true to return a single result (string), e.g.:
$key1 = get_post_meta( $post->ID, 'img-url', true );
http://codex.wordpress.org/Function_Reference/get_post_meta