Featured Posts Section on Wordpress won't show up - php

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.

Related

Wordpress php can't show custom meta info on post listings page for each post

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.

How to change image size on featured images in wordpress?

I thought I had it all figured out, when of course, the code doesn't work. Not sure what I'm doing wrong or how to fix it. I just want to be able to define image sizes in my functions.php file and call them whenever I want from my index.php or single.php. (Excuse all of the comments in the code. I'm following a tutorial trying to learn wordpress and the tutorial doesn't cover the issue of "what if it doesn't work") So currently, the image I'm playing with is 1360x582 and it will resize based on my css, but not according to the functions when I apply them. Any help would be great!
My index.php looks like this:
<?php
get_header();
if (have_posts()) :
while (have_posts()) : the_post(); ?>
<article class="post">
<h2><?php the_title(); ?></h2>
<p class="post-info"><?php the_time('F jS, Y'); ?> | by <?php the_author(); ?> | Posted in
<?php
$categories = get_the_category();
$separator = ", ";
$output = '';
if ($categories){
foreach ($categories as $category) {
$output .= '' . $category->cat_name . '' . $separator;
}
echo trim($output, $separator); //trim() removes comma from last item//
}
?></p>
<?php the_post_thumbnail('small_thumbnail'); ?> <!--featured image-->
<!-- if you want an excerpt to be displayed only if one is manually entered, otherwise show full post:
<?php if ($post->post_excerpt) { ?>
<P>
<?php echo get_the_excerpt(); ?>
Read more»
</p>
<?php } else {
the_content();
} ?>
-->
<P>
<?php echo get_the_excerpt(); ?>
Read more»
</p>
<!-- <?php the_content('Read More...'); ?> -->
</article>
<?php endwhile;
else :
echo '<p>No content found</p>';
endif;
get_footer();
?>
functions.php:
//Theme Setup
function Theme_setup() {
//Navigation Menus
register_nav_menus(array(
'primary' => __( 'Primary Menu'),
'footer' => __( 'Footer Menu'),
));
//Add Feature Image Support
add_theme_support('post-thumbnails');
add_image_size('small-thumbnail', 180, 120, true); //width, height, hard (true) or soft crop
add_image_size('banner-image', 920, 210, true);
}
add_action('after_setup_theme', 'Theme_setup');
and my single.php looks pretty much the same as my index.php at the moment except that it uses the 'banner-image' on the featured image rather than the 'small-thumnail'
the css I have applied to images is this:
/* Image Styles */
img {
max-width: 100%;
height: auto;
}
add_image_size('small-thumbnail', 180, 120, true);
Change the 180 and 120 values (width and height) and you should be good to go.
This resource might also help you:
https://wordpress.org/support/topic/set-featured-image-size
You can also control these values with a plugin called Simple Image Sizes
I fixed my own problem. In the index.php I was using small_thumbnails as opposed to small-thumbnails as I had written in my functions.php page. What a big difference a - makes as opposed to a _. And of course it was a typo solution.

Displaying Single Post from Custom Post Type

I am using the plugins and settings below. I am having some problems displaying my custom post types. I am concentrating on the printers custom post type. I have them displaying under the custom taxonomies section and have created 4 taxonomies (manufactures) so that bit is ok. (http://developmentscene.co/CKH/printers/)
The Problem
When I click on a post on the page above it displays all posts in that category. I just want it to display the post that the link you clicked on and only that post. I have tried to do this using ('posts_per_page' => 1,) But this bit of code just displays the same first post for each post I click on in the category page.
My Ideal Solution
So what I was thinking in my mind was to say only show one post with the ID of the link you clicked previously in the category. I dont know if this is the best way but I have put my code below.
<?php get_header(); ?>
<div id="wrap" class="container">
<section id="content" class="primary" role="main">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php endwhile; ?>
<?php endif; ?>
<?php $printers = new WP_Query(array(
'post_type' => 'printers',
'posts_per_page' => 1,
)); ?>
<?php while($printers->have_posts()) : $printers->the_post(the_ID()); ?>
<h2 class="post-title" style="color:#333;" ><?php the_title(); ?> - <?php echo the_ID();?></h2>
<hr >
<p><?php the_content(); ?></p>
<p> </p>
<?php the_post_thumbnail(); ?>
<br />
</section>
<section id="sidebar" class="secondary clearfix" role="complementary">
<h3 class="widgettitle" ><b>Features and Benefits</b></h3>
<?php $benefits = get_field( "features-and-benefits" );
if($benefits){
echo '<table cellspacing="0" cellpadding="0"><tbody>' ;
foreach($benefits as $benefits){
echo '<tr><td><p>' . $benefits['features'] . '</p></td></tr>' ;
}
echo '</tbody></table>';
}
?>
<br />
<h3 class="widgettitle" ><b>More Information</b></h3>
<?php $specifications = get_field( "specifications" );;
if($specifications){
echo '<table cellspacing="0" cellpadding="0"><tbody>' ;
foreach($specifications as $specifications){
echo '<tr><td><p>' . '<a target="_blank" href="http://' . $specifications['link'] . '/">' . $specifications['details'] . '</a></p></td></tr>' ;
}
echo '</tbody></table>';
}
?>
</section>
<?php endwhile; ?>
</div>
<?php get_footer(); ?>
Settings
Plugins Used:
* Custom Fields
* Custom Post Type UI
I also have permalinks set to postname.
You are running two loops here, and that is causing all the frustrations. I believe that you added the second loop for your specific needs, so can you can just simply delete the first loop, that is this section
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php endwhile; ?>
<?php endif; ?>

2 WP_Query loops for custom post types on the same page

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.

Struggling to get custom meta data to show in wordpress post

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; ?>

Categories