Don't show anything when there is no content - wordpress

I have the following code inside the search results page and I want it not to show it when there is no content in any part.
if ( have_posts() ) {
$types = array('singer', 'music', 'album');
foreach( $types as $type ){
if( $type == 'singer'){
echo ' <h1>Singers</h1> ';
} elseif ( $type == 'music'){
echo '<h1>Musics</h1>';
}
elseif ( $type == 'album'){
echo '<h1>Albums</h1>';
}
while( have_posts() ){
the_post();
if( $type == get_post_type() ){
the_post_thumbnail('medium'); ?>
<h3><a href="<?php echo get_permalink(); ?>">
<?php the_title(); ?>
</a></h3>
<?php
}
}
rewind_posts();
}
} else {
echo us_translate( 'No results found.' );
}

This is not a good solution, but should work)
$types = array(
'singer' => array( 'title' => 'Singers', 'content' => '' ),
'music' => array( 'title' => 'Musics', 'content' => '' ),
'album' => array( 'title' => 'Albums', 'content' => '' ),
);
if ( have_posts() ) {
while( have_posts() ) {
the_post();
$type = get_post_type();
if ( array_key_exists( $type, $types ) ) {
$types[ $type ][ 'content' ] .= get_the_post_thumbnail( null, 'medium' );
$types[ $type ][ 'content' ] .= '<h3><a href="' . get_the_permalink() . '">' . get_the_title() . '</h3>';
}
}
foreach( $types as $k => $v ) {
if ( $v[ 'content' ] ) {
echo '<h1>' . $v[ 'title' ]. '</h1>' . $v[ 'content' ];
}
}
} else {
echo us_translate( 'No results found.' );
}

Related

Woocommerce Widget Custom Price with Thousand separator and Decimal separator

I am using a template which has a widget to show woocommetce product on the home page, Currently price of product is just a number E.g. ₹18500/- without any decimal or comma, I want to show price with Thousand separator and Decimal separator E.g. ₹ 18,500/-
Note: Thousand separator and Decimal separator is enabled from woocommerce settings, and here I want to show price on a widget.
I am attaching code of the widget.
any help will be appreciated.
* Filter the arguments for the Recent Posts widget.
*
* #since 1.0.0
*
* #see WP_Query
*
*/
$query_args = array(
'posts_per_page' => $post_number,
'post_status' => 'publish',
'post_type' => 'product',
'no_found_rows' => 1,
'order' => $order,
'meta_query' => array(),
'tax_query' => array(
'relation' => 'AND',
),
);
switch ( $wc_advanced_option ) {
case 'featured' :
if( !empty( $product_visibility_term_ids['featured'] )){
$query_args['tax_query'][] = array(
'taxonomy' => 'product_visibility',
'field' => 'term_taxonomy_id',
'terms' => $product_visibility_term_ids['featured'],
);
}
break;
case 'onsale' :
$product_ids_on_sale = wc_get_product_ids_on_sale();
if( !empty( $product_ids_on_sale ) ){
$query_args['post__in'] = $product_ids_on_sale;
}
break;
case 'cat' :
if( !empty( $travel_way_wc_product_cat )){
$query_args['tax_query'][] = array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $travel_way_wc_product_cat,
);
}
break;
case 'tag' :
if( !empty( $travel_way_wc_product_tag )){
$query_args['tax_query'][] = array(
'taxonomy' => 'product_tag',
'field' => 'term_id',
'terms' => $travel_way_wc_product_tag,
);
}
break;
}
switch ( $orderby ) {
case 'price' :
$query_args['meta_key'] = '_price';
$query_args['orderby'] = 'meta_value_num';
break;
case 'sales' :
$query_args['meta_key'] = 'total_sales';
$query_args['orderby'] = 'meta_value_num';
break;
case 'ID' :
case 'author' :
case 'title' :
case 'date' :
case 'modified' :
case 'rand' :
case 'comment_count' :
case 'menu_order' :
$query_args['orderby'] = $orderby;
break;
default :
$query_args['orderby'] = 'date';
}
$travel_way_featured_query = new WP_Query( $query_args );
if ($travel_way_featured_query->have_posts()) :
echo $args['before_widget'];
$animation = "init-animate zoomIn";
?>
<section id="<?php echo esc_attr( $unique_id ); ?>" class="at-widgets acme-abouts <?php echo $bg_gray_class;?>">
<div class="container">
<?php
if ( ! empty( $title ) ) {
echo $args['before_title'] . esc_html( $title ) . $args['after_title'];
}
$div_attr = 'class="featured-entries-col woocommerce"';
?>
<div class="row at-cat-product-wrap clearfix ">
<div <?php echo $div_attr;?>>
<?php
$travel_way_featured_index = 1;
while ( $travel_way_featured_query->have_posts() ) :$travel_way_featured_query->the_post();
$travel_way_list_classes = 'single-list';
if ( 1 == $column_number ) {
$travel_way_list_classes .= " col-sm-12";
} elseif ( 2 == $column_number ) {
$travel_way_list_classes .= " col-sm-6";
} elseif ( 3 == $column_number ) {
$travel_way_list_classes .= " col-sm-4 col-md-4";
} else {
$travel_way_list_classes .= " col-sm-4 col-md-3";
}
?>
<div class="<?php echo esc_attr( $travel_way_list_classes ); ?>">
<a href="<?php the_permalink();?>">
<?php the_post_thumbnail($travel_way_img_size)?>
<div class="caption">
<h3 class="at-woo-title"><?php the_title();?></h3>
<?php
woocommerce_template_loop_rating();
$currency = get_woocommerce_currency_symbol();
$price = get_post_meta( get_the_ID(), '_regular_price', true);
$sale = get_post_meta( get_the_ID(), '_sale_price', true);
if($sale) :
global $post, $product;
echo apply_filters( 'woocommerce_sale_flash', '<span class="onsale">' . esc_html__( 'Sale!', 'travel-way' ) . '</span>', $post, $product );
?>
<p class="product-price">
<del>
<?php
echo esc_html($currency);
echo esc_html( $price );
?>
</del>
<?php
echo esc_html($currency);
echo esc_html( $sale . '/-' );
?>
</p>
<?php elseif($price) : ?>
<p class="product-price">
<?php
echo esc_html($currency);
echo esc_html( $price . '/-');
?>
</p>
<?php endif;
?>
</div>
</a>
</div><!--dynamic css-->
<?php
$travel_way_featured_index++;
endwhile;
?>
</div><!--featured entries-col-->
</div><!--cat product wrap-->
<?php
echo $args['after_widget'];
echo "<div class='clearfix'></div>";
// Reset the global $the_post as this query will have stomped on it
?>
</div>
</section>
<?php
endif;
wp_reset_postdata();
}
} // Class Travel_Way_Wc_Products ends here
} ```
You can use number_format. Should be something like:
$price = floatval($price);
$decimal_separator = wc_get_price_decimal_separator();
$thousand_separator = wc_get_price_thousand_separator();
$decimals = wc_get_price_decimals();
$formatted_price = number_format( $price, $decimals, $decimal_separator, $thousand_separator );
echo esc_html( $formatted_price . '/-');

Wordpress pagination give duplicate content

So i change my wordpress permalink with custom structure "/%category%/%postname%/".
However, if i type manually "/poem/page/2", then it works. But the content of every page is the same. Wether it was "/page/3" or "/page/4", it was all the same.
at first, when i access "/page/2/", my page was giving "404 error". But i got this code from the internet, and when i use the code, it started to work. But, the content of every page is the same. The code goes on like this :
on function.php:
function vipx_filter_category_rewrite_rules( $rules ) {
$categories = get_categories( array( 'hide_empty' => false ) );
if ( is_array( $categories ) && ! empty( $categories ) ) {
$slugs = array();
foreach ( $categories as $category ) {
if ( is_object( $category ) && ! is_wp_error( $category ) ) {
if ( 0 == $category->category_parent ) {
$slugs[] = $category->slug;
} else {
$slugs[] = trim( get_category_parents( $category->term_id, false, '/', true ), '/' );
}
}
}
if ( ! empty( $slugs ) ) {
$rules = array();
foreach ( $slugs as $slug ) {
$rules[ '(' . $slug . ')/feed/(feed|rdf|rss|rss2|atom)?/?$' ] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
$rules[ '(' . $slug . ')/(feed|rdf|rss|rss2|atom)/?$' ] = 'index.php?category_name=$matches[1]&feed=$matches[2]';
$rules[ '(' . $slug . ')(/page/(\d)+/?)?$' ] = 'index.php?category_name=$matches[1]&paged=$matches[3]';
}
}
}
return $rules;
}```
this is my loop post :
?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
echo $paged;
$term = get_queried_object();
$data = array( 'posts_per_page' => 2, 'category_name' => $term->slug, 'page'=>$paged );
$get_category_post = new WP_Query( $data );
?>
<?php if ( $get_category_post->have_posts() ) : while ( $get_category_post->have_posts() ) : $get_category_post->the_post(); ?>
<div class="post__list">
<?php if($term->slug === 'analect' || $term->slug === 'collection') { ?>
<span>for other categories</span>
<?php } else {?>
<span> <?php the_content(); ?> </span>
<?php } ?>
</div>
<?php endwhile; ?>
<?php
next_posts_link();
previous_posts_link();
?>
<?php endif; ?>

set post per page using get_post_meta

I have code to show get_meta_post per page this my code
if ( have_posts() ) :
while ( have_posts() ) : the_post();
$metas = get_post_meta(get_the_ID(),'value_gallery',false);
//var_dump($metas); ==> will output array(1) { [0]=> string(29) "1434,1402,1434,1435,1398,1434" }
foreach ($metas as $key ) {
$key_val = explode(",", $key);
$page = get_query_var('page');
$page = $page > 1 ? $page - 1 : 0 ;
if (isset($key_val[$page])) {
echo "<div class='col-lg-4'>".
wp_get_attachment_image($key_val[$page],"cherry-thumb-a") ."</div>";
}
}
endwhile;
else :
_e('Sorry, no posts matched your criteria.');
endif;
so this code will show my image using
wp_get_attachment_image($key_val[$page],"cherry-thumb-a")
and will paginate with link
https://yourpage.com/post-name/2
but this code just show image 1 per page , my problem is how to show 4 image per page , and how to change link paginate to
https://yourpage.com/post-name/page/2
i will hapyy if anyone can help me
Update
thankyou for attention , i was try adding array_chunk , and adding pagination , but it still not work , my full code:
$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
$args = array('posts_per_page' => 1, 'paged' => $paged );
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
$metas = get_post_meta(get_the_ID(),'value_gallery',false);
foreach ($metas as $meta) {
$key_val = explode(",", $meta);
$image_chunk = array_chunk($key_val, 4);
$page = get_query_var('page');
$page = $page > 1 ? $page - 1 : 0 ;
if (isset($key_val[$page])) {
foreach ($image_chunk[$page] as $image) {
echo "<div class='col-lg-4'>".
wp_get_attachment_image($image,"cherry-thumb-a") ."</div>";
}
}
}
endwhile;
$big = 999999999;
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $the_query->max_num_pages
) );
endif;
many thank for attention
use array_chunk()
if ( have_posts() ) :
while ( have_posts() ) : the_post();
$metas = get_post_meta(get_the_ID(),'value_gallery',false);
foreach ($metas as $meta) {
$key_val = explode(",", $meta);
$image_chunk = array_chunk($key_val, 4);
$page = get_query_var('page');
$page = $page > 1 ? $page - 1 : 0 ;
if (isset($key_val[$page])) {
foreach ($image_chunk[$page] as $image) {
echo "<div class='col-lg-4'>".
wp_get_attachment_image($image,"cherry-thumb-a") ."</div>";
}
}
}
endwhile;
endif;
Adding pagination for single post pages
Place this function in your functions.php
add_action('redirect_canonical', 'single_pagination_fix');
public static function single_pagination_fix( $redirect_url ) {
if ( is_paged() && is_singular() ) {
$redirect_url = false;
}
return $redirect_url;
}

How to show "Published on"-date instead of "Last edited"-date in wordpress post's

I have a theme for a blog in which im trying to modify, so that it always shows the "published date" instead for "Edited on" every time I edit it...
I have nailed it down to the file -> functions.php where it displays the dates... Section "Posted On Function"
But everytime i try to modify the if/else i get a error 500 on the page :-(
Some help would be highly appreciated here...
Thanks in advance!
-Best regards
Part that I suspect is the reason :
-------------------------------------------------------------------------------------------------------
Posted On Function
-------------------------------------------------------------------------------------------------------
*/
function swell_posted_on() {
if ( get_the_modified_time() != get_the_time() ) {
printf( __( '<span class="%1$s">Last Updated:</span> %2$s', 'organic-swell' ),
'meta-prep meta-prep-author',
sprintf( '<span class="entry-date">%3$s</span>',
esc_url( get_permalink() ),
esc_attr( get_the_modified_time() ),
get_the_modified_date()
)
);
} else {
printf( __( '<span class="%1$s">Posted:</span> %2$s', 'organic-swell' ),
'meta-prep meta-prep-author',
sprintf( '<span class="entry-date">%3$s</span>',
esc_url( get_permalink() ),
esc_attr( get_the_time() ),
get_the_date()
)
);
}
}
/*
This is the entire functions.php file :
/*
-------------------------------------------------------------------------------------------------------
Theme Setup
-------------------------------------------------------------------------------------------------------
*/
if ( ! function_exists( 'swell_setup' ) ) :
function swell_setup() {
// Make theme available for translation.
load_theme_textdomain( 'organic-swell', get_template_directory() . '/languages' );
// Add default posts and comments RSS feed links to head.
add_theme_support( 'automatic-feed-links' );
// Enable support for Post Thumbnails.
add_theme_support( 'post-thumbnails' );
// Enable support for site title tag.
add_theme_support( 'title-tag' );
add_image_size( 'swell-featured-large', 1800, 1200, true ); // Large Featured Image.
add_image_size( 'swell-featured-medium', 1200, 800, true ); // Medium Featured Image.
add_image_size( 'swell-featured-small', 640, 640, true ); // Small Featured Image.
// Post Formats.
add_theme_support( 'post-formats', array(
'gallery',
'link',
'image',
'audio',
'status',
'quote',
'video',
)
);
// Create Menus.
register_nav_menus( array(
'fixed-menu' => esc_html__( 'Fixed Menu', 'organic-swell' ),
'main-menu' => esc_html__( 'Main Menu', 'organic-swell' ),
'social-menu' => esc_html__( 'Social Menu', 'organic-swell' ),
));
// Custom Header.
register_default_headers( array(
'default' => array(
'url' => get_template_directory_uri() . '/images/default-header.jpg',
'thumbnail_url' => get_template_directory_uri() . '/images/default-header.jpg',
'description' => esc_html__( 'Default Custom Header', 'organic-swell' ),
),
));
$defaults = array(
'width' => 1800,
'height' => 480,
'flex-height' => true,
'flex-width' => true,
'default-text-color' => 'ffffff',
'default-image' => get_template_directory_uri() . '/images/default-header.jpg',
'header-text' => false,
'uploads' => true,
);
add_theme_support( 'custom-header', $defaults );
// Custom Background.
$defaults = array(
'default-color' => 'eeeeee',
);
add_theme_support( 'custom-background', $defaults );
}
endif; // swell_setup
add_action( 'after_setup_theme', 'swell_setup' );
/*
-------------------------------------------------------------------------------------------------------
Theme Updater
-------------------------------------------------------------------------------------------------------
*/
function swell_theme_updater() {
require( get_template_directory() . '/updater/theme-updater.php' );
}
add_action( 'after_setup_theme', 'swell_theme_updater' );
/*
-------------------------------------------------------------------------------------------------------
Category ID to Name
-------------------------------------------------------------------------------------------------------
*/
function swell_cat_id_to_name( $id ) {
$cat = get_category( $id );
if ( is_wp_error( $cat ) ) {
return false; }
return $cat->cat_name;
}
/*
-------------------------------------------------------------------------------------------------------
Register Scripts
-------------------------------------------------------------------------------------------------------
*/
if ( ! function_exists( 'swell_enqueue_scripts' ) ) {
function swell_enqueue_scripts() {
// Enqueue Styles.
wp_enqueue_style( 'swell-style', get_stylesheet_uri() );
wp_enqueue_style( 'swell-style-mobile', get_template_directory_uri() . '/css/style-mobile.css', array( 'swell-style' ), '1.0' );
// Resgister Scripts.
wp_register_script( 'swell-fitvids', get_template_directory_uri() . '/js/jquery.fitvids.js', array( 'jquery' ), '20130729' );
wp_register_script( 'swell-hover', get_template_directory_uri() . '/js/hoverIntent.js', array( 'jquery' ), '20130729' );
wp_register_script( 'swell-superfish', get_template_directory_uri() . '/js/superfish.js', array( 'jquery', 'swell-hover' ), '20130729' );
// Enqueue Scripts.
wp_enqueue_script( 'swell-custom', get_template_directory_uri() . '/js/jquery.custom.js', array( 'jquery', 'swell-superfish', 'swell-fitvids', 'masonry' ), '20130729', true );
wp_enqueue_script( 'swell-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20130729', true );
// Load Flexslider on front page and slideshow page template.
if ( is_home() || is_front_page() || is_single() || is_page_template( 'template-slideshow.php' ) || is_page_template( 'template-featured-content.php' ) ) {
wp_enqueue_script( 'swell-flexslider', get_template_directory_uri() . '/js/jquery.flexslider.js', array( 'jquery' ), '20130729' );
}
// Load single scripts only on single pages.
if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
wp_enqueue_script( 'comment-reply' );
}
}
}
add_action( 'wp_enqueue_scripts', 'swell_enqueue_scripts' );
/*
-------------------------------------------------------------------------------------------------------
Register Sidebars
-------------------------------------------------------------------------------------------------------
*/
function swell_widgets_init() {
register_sidebar(array(
'name' => esc_html__( 'Default Sidebar', 'organic-swell' ),
'id' => 'default-sidebar',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h6 class="title">',
'after_title' => '</h6>',
));
register_sidebar(array(
'name' => esc_html__( 'Blog Sidebar', 'organic-swell' ),
'id' => 'blog-sidebar',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h6 class="title">',
'after_title' => '</h6>',
));
register_sidebar(array(
'name' => esc_html__( 'Left Sidebar', 'organic-swell' ),
'id' => 'left-sidebar',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h6 class="title">',
'after_title' => '</h6>',
));
register_sidebar(array(
'name' => esc_html__( 'Footer Widgets', 'organic-swell' ),
'id' => 'footer',
'before_widget' => '<div id="%1$s" class="widget %2$s"><div class="footer-widget">',
'after_widget' => '</div></div>',
'before_title' => '<h6 class="title">',
'after_title' => '</h6>',
));
}
add_action( 'widgets_init', 'swell_widgets_init' );
/*
-------------------------------------------------------------------------------------------------------
Add Stylesheet To Visual Editor
-------------------------------------------------------------------------------------------------------
*/
add_action( 'widgets_init', 'swell_add_editor_styles' );
/**
* Apply theme's stylesheet to the visual editor.
*
* #uses add_editor_style() Links a stylesheet to visual editor
* #uses get_stylesheet_uri() Returns URI of theme stylesheet
*/
function swell_add_editor_styles() {
add_editor_style( 'css/style-editor.css' );
}
/*
-------------------------------------------------------------------------------------------------------
Posted On Function
-------------------------------------------------------------------------------------------------------
*/
function swell_posted_on() {
if ( get_the_modified_time() != get_the_time() ) {
printf( __( '<span class="%1$s">Last Updated:</span> %2$s', 'organic-swell' ),
'meta-prep meta-prep-author',
sprintf( '<span class="entry-date">%3$s</span>',
esc_url( get_permalink() ),
esc_attr( get_the_modified_time() ),
get_the_modified_date()
)
);
} else {
printf( __( '<span class="%1$s">Posted:</span> %2$s', 'organic-swell' ),
'meta-prep meta-prep-author',
sprintf( '<span class="entry-date">%3$s</span>',
esc_url( get_permalink() ),
esc_attr( get_the_time() ),
get_the_date()
)
);
}
}
/*
-------------------------------------------------------------------------------------------------------
Post Format Meta Boxes
-------------------------------------------------------------------------------------------------------
*/
add_action( 'admin_init', 'create_metaboxes' );
add_action( 'save_post', 'save_metaboxes' );
$metaboxes = array(
'link_url' => array(
'title' => esc_html__( 'Link Information', 'organic-swell' ),
'applicableto' => 'post',
'location' => 'side',
'display_condition' => 'post-format-link',
'priority' => 'default',
'fields' => array(
'l_url' => array(
'title' => esc_html__( 'Link URL: ', 'organic-swell' ),
'type' => 'text',
'description' => '',
'size' => 20,
),
),
),
'quote_author' => array(
'title' => esc_html__( 'Quote Author', 'organic-swell' ),
'applicableto' => 'post',
'location' => 'side',
'display_condition' => 'post-format-quote',
'priority' => 'default',
'fields' => array(
'q_author' => array(
'title' => esc_html__( 'Author: ', 'organic-swell' ),
'type' => 'text',
'description' => '',
'size' => 20,
),
),
),
);
function create_metaboxes() {
global $metaboxes;
if ( ! empty( $metaboxes ) ) {
foreach ( $metaboxes as $id => $metabox ) {
add_meta_box( $id, $metabox['title'], 'show_metaboxes', $metabox['applicableto'], $metabox['location'], $metabox['priority'], $id );
}
}
}
function show_metaboxes( $post, $args ) {
global $metaboxes;
$custom = get_post_custom( $post->ID );
$fields = $tabs = $metaboxes[ $args['id'] ]['fields'];
/** Nonce */
$output = '<input type="hidden" name="post_format_meta_box_nonce" value="' . wp_create_nonce( basename( __FILE__ ) ) . '" />';
if ( sizeof( $fields ) ) {
foreach ( $fields as $id => $field ) {
switch ( $field['type'] ) {
default:
case 'text':
if ( isset( $custom[ $id ] ) ) {
$output .= '<label for="' . esc_attr( $id ) . '">' . $field['title'] . '</label><input id="' . esc_attr( $id ) . '" type="text" name="' . esc_attr( $id ) . '" value="' . $custom[ $id ][0] . '" size="' . $field['size'] . '" />';
} else {
$output .= '<label for="' . esc_attr( $id ) . '">' . $field['title'] . '</label><input id="' . esc_attr( $id ) . '" type="text" name="' . esc_attr( $id ) . '" value="" size="' . $field['size'] . '" />';
}
break;
}
}
}
echo $output;
}
function save_metaboxes( $post_id ) {
global $metaboxes;
// Verify nonce.
if ( isset( $_POST['post_format_meta_box_nonce'] ) && ! wp_verify_nonce( $_POST['post_format_meta_box_nonce'], basename( __FILE__ ) ) ) {
return $post_id; }
// Check autosave.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return $post_id; }
// Check permissions.
if ( 'page' == isset( $_POST['post_type'] ) ) {
if ( ! current_user_can( 'edit_page', $post_id ) ) {
return $post_id; }
} elseif ( ! current_user_can( 'edit_post', $post_id ) ) {
return $post_id;
}
$post_type = get_post_type();
// Loop through fields and save the data.
foreach ( $metaboxes as $id => $metabox ) {
// Check if metabox is applicable for current post type.
if ( $metabox['applicableto'] == $post_type ) {
$fields = $metaboxes[ $id ]['fields'];
foreach ( $fields as $id => $field ) {
$old = get_post_meta( $post_id, $id, true );
$new = $_POST[ $id ];
if ( $new && $new != $old ) {
update_post_meta( $post_id, $id, $new );
} elseif ( '' == $new && $old || ! isset( $_POST[ $id ] ) ) {
delete_post_meta( $post_id, $id, $old );
}
}
}
}
}
add_action( 'admin_print_scripts', 'display_metaboxes', 1000 );
function display_metaboxes() {
global $metaboxes;
if ( get_post_type() == 'post' ) :
?>
<script type="text/javascript"> // <![CDATA[
$ = jQuery;
<?php
$formats = $ids = array();
foreach ( $metaboxes as $id => $metabox ) {
array_push( $formats, "'" . $metabox['display_condition'] . "': '" . $id . "'" );
array_push( $ids, '#' . $id );
}
?>
var formats = { <?php echo implode( ',', $formats );?> };
var ids = "<?php echo implode( ',', $ids ); ?>";
function displayMetaboxes() {
// Hide all post format metaboxes.
$(ids).hide();
// Get current post format.
var selectedElt = $("input[name='post_format']:checked").attr("id");
// If exists, fade in current post format metabox.
if ( formats[selectedElt] )
$("#" + formats[selectedElt]).fadeIn();
}
$(function() {
// Show/hide metaboxes on page load
displayMetaboxes();
// Show/hide metaboxes on change event
$("input[name='post_format']").change(function() {
displayMetaboxes();
});
});
// ]]></script>
<?php
endif;
}
/*
-------------------------------------------------------------------------------------------------------
Content Width
-------------------------------------------------------------------------------------------------------
*/
if ( ! isset( $content_width ) ) {
$content_width = 640; }
/**
* Adjust content_width value based on the presence of widgets
*/
function swell_content_width() {
if ( ! is_active_sidebar( 'post-sidebar' ) || is_active_sidebar( 'page-sidebar' ) || is_active_sidebar( 'blog-sidebar' ) ) {
global $content_width;
$content_width = 960;
}
}
add_action( 'template_redirect', 'swell_content_width' );
/*
-------------------------------------------------------------------------------------------------------
Comments Function
-------------------------------------------------------------------------------------------------------
*/
if ( ! function_exists( 'swell_comment' ) ) :
function swell_comment( $comment, $args, $depth ) {
$GLOBALS['comment'] = $comment;
switch ( $comment->comment_type ) :
case 'pingback' :
case 'trackback' :
?>
<li class="post pingback">
<p><?php esc_html_e( 'Pingback:', 'organic-swell' ); ?> <?php comment_author_link(); ?><?php edit_comment_link( esc_html__( 'Edit', 'organic-swell' ), '<span class="edit-link">', '</span>' ); ?></p>
<?php
break;
default :
?>
<li <?php comment_class(); ?> id="<?php echo esc_attr( 'li-comment-' . get_comment_ID() ); ?>">
<article id="<?php echo esc_attr( 'comment-' . get_comment_ID() ); ?>" class="comment">
<footer class="comment-meta">
<div class="comment-author vcard">
<?php
$avatar_size = 72;
if ( '0' != $comment->comment_parent ) {
$avatar_size = 48; }
echo get_avatar( $comment, $avatar_size );
/* translators: 1: comment author, 2: date and time */
printf( __( '%1$s <br/> %2$s <br/>', 'organic-swell' ),
sprintf( '<span class="fn">%s</span>', wp_kses_post( get_comment_author_link() ) ),
sprintf( '<time pubdate datetime="%2$s">%3$s</time>',
esc_url( get_comment_link( $comment->comment_ID ) ),
get_comment_time( 'c' ),
/* translators: 1: date, 2: time */
sprintf( __( '%1$s', 'organic-swell' ), get_comment_date(), get_comment_time() )
)
);
?>
</div><!-- .comment-author .vcard -->
</footer>
<div class="comment-content">
<?php if ( $comment->comment_approved == '0' ) : ?>
<em class="comment-awaiting-moderation"><?php esc_html_e( 'Your comment is awaiting moderation.', 'organic-swell' ); ?></em>
<br />
<?php endif; ?>
<?php comment_text(); ?>
<div class="reply">
<?php comment_reply_link( array_merge( $args, array( 'reply_text' => esc_html__( 'Reply', 'organic-swell' ), 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?>
</div><!-- .reply -->
<?php edit_comment_link( esc_html__( 'Edit', 'organic-swell' ), '<span class="edit-link">', '</span>' ); ?>
</div>
</article><!-- #comment-## -->
<?php
break;
endswitch;
}
endif; // Ends check for swell_comment().
/*
-------------------------------------------------------------------------------------------------------
Disable Comments On Pages Default
-------------------------------------------------------------------------------------------------------
*/
function swell_default_comments_off( $data ) {
if ( $data['post_type'] == 'page' && $data['post_status'] == 'auto-draft' ) {
$data['comment_status'] = 0;
}
return $data;
}
add_filter( 'wp_insert_post_data', 'swell_default_comments_off' );
/*
-------------------------------------------------------------------------------------------------------
Custom Excerpt Length
-------------------------------------------------------------------------------------------------------
*/
function swell_excerpt_length( $length ) {
return 38;
}
add_filter( 'excerpt_length', 'swell_excerpt_length', 999 );
function swell_excerpt_more( $more ) {
return '... <a class="read-more" href="'. get_permalink( get_the_ID() ) . '">'. esc_html__( 'Read More', 'organic-swell' ) .'</a>';
}
add_filter( 'excerpt_more', 'swell_excerpt_more' );
/*
-------------------------------------------------------------------------------------------------------
Add Excerpt To Pages
-------------------------------------------------------------------------------------------------------
*/
add_action( 'widgets_init', 'swell_add_excerpts_to_pages' );
function swell_add_excerpts_to_pages() {
add_post_type_support( 'page', 'excerpt' );
}
/*
-------------------------------------------------------------------------------------------------------
Custom Page Links
-------------------------------------------------------------------------------------------------------
*/
function swell_wp_link_pages_args_prevnext_add( $args ) {
global $page, $numpages, $more, $pagenow;
if ( ! $args['next_or_number'] == 'next_and_number' ) {
return $args; }
$args['next_or_number'] = 'number'; // Keep numbering for the main part
if ( ! $more ) {
return $args; }
if ( $page -1 ) { // There is a previous page
$args['before'] .= _wp_link_page( $page -1 )
. $args['link_before']. $args['previouspagelink'] . $args['link_after'] . '</a>'; }
if ( $page < $numpages ) { // There is a next page
$args['after'] = _wp_link_page( $page + 1 )
. $args['link_before'] . $args['nextpagelink'] . $args['link_after'] . '</a>'
. $args['after']; }
return $args;
}
add_filter( 'wp_link_pages_args', 'swell_wp_link_pages_args_prevnext_add' );
/*
-------------------------------------------------------------------------------------------------------
Featured Video Meta Box
-------------------------------------------------------------------------------------------------------
*/
add_action( 'admin_init', 'admin_init_featurevid' );
add_action( 'save_post', 'save_featurevid' );
function admin_init_featurevid() {
add_meta_box( 'featurevid-meta', esc_html__( 'Featured Video Embed Code', 'organic-swell' ), 'meta_options_featurevid', 'post', 'normal', 'high' );
}
function meta_options_featurevid() {
global $post;
$custom = get_post_custom( $post->ID );
$featurevid = isset( $custom['featurevid'] ) ? esc_attr( $custom['featurevid'][0] ) : '';
echo '<textarea name="featurevid" cols="60" rows="4" style="width:97.6%" />'.$featurevid.'</textarea>';
}
function save_featurevid( $post_id ) {
global $post;
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return $post_id;
}
if ( isset( $_POST['featurevid'] ) ) {
update_post_meta( $post->ID, 'featurevid', $_POST['featurevid'] );
}
}
/*
-------------------------------------------------------------------------------------------------------
Remove First Gallery
-------------------------------------------------------------------------------------------------------
*/
function swell_remove_gallery( $content ) {
if ( is_page_template( 'template-slideshow.php' ) || has_post_format( 'gallery' ) || ( is_singular( 'jetpack-portfolio' ) && get_theme_mod( 'display_project_slideshow', false ) ) ) {
$content = preg_replace( '/\[gallery(.*?)ids=[^\]]+\]/', '', $content, 1 );
}
return $content;
}
add_filter( 'the_content', 'swell_remove_gallery' );
/*
-------------------------------------------------------------------------------------------------------
Home Link In Custom Menu
-------------------------------------------------------------------------------------------------------
*/
function home_page_menu_args( $args ) {
$args['show_home'] = true;
return $args;
}
add_filter( 'wp_page_menu_args', 'home_page_menu_args' );
/*
-------------------------------------------------------------------------------------------------------
Body Class
-------------------------------------------------------------------------------------------------------
*/
function swell_body_class( $classes ) {
if ( is_singular() ) {
$classes[] = 'swell-singular'; }
if ( is_active_sidebar( 'right-sidebar' ) ) {
$classes[] = 'swell-right-sidebar'; }
if ( '' != get_theme_mod( 'background_image' ) ) {
// This class will render when a background image is set
// regardless of whether the user has set a color as well.
$classes[] = 'swell-background-image';
} else if ( ! in_array( get_background_color(), array( '', get_theme_support( 'custom-background', 'default-color' ) ) ) ) {
// This class will render when a background color is set
// but no image is set. In the case the content text will
// Adjust relative to the background color.
$classes[] = 'swell-relative-text';
}
return $classes;
}
add_action( 'body_class', 'swell_body_class' );
/*
-------------------------------------------------------------------------------------------------------
Includes
-------------------------------------------------------------------------------------------------------
*/
require_once( get_template_directory() . '/includes/jetpack.php' );
require_once( get_template_directory() . '/includes/customizer.php' );
require_once( get_template_directory() . '/includes/typefaces.php' );
require_once( get_template_directory() . '/includes/woocommerce-setup.php' );
require_once( get_template_directory() . '/includes/plugin-activation.php' );
require_once( get_template_directory() . '/includes/plugin-activation-class.php' );
Change this line
if ( get_the_modified_time() != get_the_time() ) {
to
if ( get_the_modified_time() != get_the_time() && false ) {

Wordpress - Post Category on page

I have a question: In wordpress, how can I display posts in a category on a page ?. I have many categories, and in a page, I just only want posts in a category are displayed.
Thanks for your support !
Here is an alternative to a plugin. This is a dynamic page template. This template lets you choose which category's posts to display on the specific page. You can use this template over and over inside the same theme
Add this to your functions.php or any functions related file
<?php
/**-----------------------------------------------------------------------------
*
*Add a post metabox with options to the admin page screen.
*After selcting the page-pop.php template as a page template,
*this metabox will appear in the admin page screen.
*From here you can choose which category's posts to display
*and how the posts will be displayed on the page
*
* #package WordPress
* #subpackage Twenty_Fourteen
* #since Twenty Fourteen 1.0
*
*------------------------------------------------------------------------------*/
/**-----------------------------------------------------------------------------
*
*1. Only add meta boxes for the pop template
*
* #since Twenty Fourteen 1.0
*
*------------------------------------------------------------------------------*/
add_action('admin_init', 'pietergoosen_add_pop_meta_box');
function pietergoosen_add_pop_meta_box(){
$post_id = isset( $_GET['post'] ) ? $_GET['post'] : 0 ;
if($post_id) {
$template_file = get_post_meta($post_id,'_wp_page_template',TRUE);
if ($template_file == 'page-pop.php') {
add_meta_box('pop_meta_box', __( 'Page of Posts with the same name', 'pietergoosen' ), 'pietergoosen_pop_meta_options', 'page', 'side', 'core');
} else {
$meta = get_post_meta($post_id, '_cat_id', true);
if( $meta ) {
pietergoosen_pop_update_post_meta($post_id, '_cat_id', '');
pietergoosen_pop_update_post_meta($post_id, '_page_title', '');
pietergoosen_pop_update_post_meta($post_id, '_posts_title', '');
pietergoosen_pop_update_post_meta($post_id, '_order_by', '');
pietergoosen_pop_update_post_meta($post_id, '_asc', '');
pietergoosen_pop_update_post_meta($post_id, '_post_count', '');
pietergoosen_pop_update_post_meta($post_id, '_days', '');
remove_meta_box( 'pop_meta_box', 'page', 'side' );
}
}
}
add_action('save_post', 'pietergoosen_pop_update_post_meta_box');
}
/**-----------------------------------------------------------------------------
*
*2. Built the list to display the options in the metabox
*
* #since Twenty Fourteen 1.0
*
*------------------------------------------------------------------------------*/
$order_list = array(
'none' => array( 'value' => 'none','label' => 'None' ),
'id' => array( 'value' => 'ID','label' => 'Post ID' ),
'author' => array( 'value' => 'author','label' => 'Author' ),
'title' => array( 'value' => 'title','label' => 'Post Title' ),
'date' => array( 'value' => 'date', 'label' => 'Post Date'),
'modified' => array( 'value' => 'modified','label' => 'Modified Date' ),
'parent' => array( 'value' => 'parent','label' => 'Parent Post' ),
'rand' => array( 'value' => 'rand','label' => 'Random' ),
'comment_count' => array( 'value' => 'comment_count','label' => 'Comment Count' ),
'menu_order' => array( 'value' => 'menu_order','label' => 'Menu Order' ),
);
$sort = array(
'DESC' => array( 'value' => 'DESC','label' => 'Descending' ),
'ASC' => array( 'value' => 'ASC','label' => 'Ascending' ),
);
function pietergoosen_pop_meta_options(){
$post_id = !empty($_GET['post']) ? $_GET['post'] : 0;
if( !$post_id ) return;
$template_file = get_post_meta($post_id,'_wp_page_template',TRUE);
if ($template_file != 'page-pop.php') return;
global $order_list,$post_styles,$sort;
$categories = get_categories();
//Check if we have values
$post_meta=array();
$post_meta = get_post_meta( $post_id,false );
$cat_id = isset( $post_meta['_cat_id'] ) ? $post_meta['_cat_id'][0] : 1;
$page_title = isset( $post_meta['_page_title'] ) && $post_meta['_page_title'] ? $post_meta['_page_title'][0] : '';
$posts_title = isset( $post_meta['_posts_title'] ) && $post_meta['_posts_title'] ? $post_meta['_posts_title'][0] : '';
$order_by = isset( $post_meta['_order_by'] ) ? $post_meta['_order_by'][0] : 'date';
$asc = isset( $post_meta['_asc'] ) ? $post_meta['_asc'][0] : 'DESC';
$post_count = isset( $post_meta['_post_count'] ) ? $post_meta['_post_count'][0] : get_option('posts_per_page');
if(!$post_count || !is_numeric( $post_count )) $post_count = get_option('posts_per_page');
$days = isset( $post_meta['_days'] ) ? $post_meta['_days'][0] : '0';
if($days && !is_numeric( $days )) $days = '0';
?>
<!-- Sart the meta boxes -->
<div class="inside">
<p><label><strong><?php _e( 'Page Title', 'pietergoosen' ); ?></strong></label></p>
<input id="_posts_title" name="_posts_title" type="text" style="width: 98%;" value="<?php echo $posts_title; ?>"/>
<p><label><strong><?php _e( 'Post Title', 'pietergoosen' ); ?></strong></label></p>
<input id="_page_title" name="_page_title" type="text" style="width: 98%;" value="<?php echo $page_title; ?>"/>
<p><label><strong><?php _e( 'Category', 'pietergoosen' ); ?></strong></label></p>
<select id="_cat_id" name="_cat_id">
<?php
//Category List
foreach ($categories as $cat) :
$selected = ( $cat->cat_ID == $cat_id ) ? ' selected = "selected" ' : '';
$option = '<option '.$selected .'value="' . $cat->cat_ID;
$option = $option .'">';
$option = $option .$cat->cat_name;
$option = $option .'</option>';
echo $option;
endforeach;
?>
</select>
<p><label><strong><?php _e( 'Sort by', 'pietergoosen' )?></strong></label></p>
<select id="_order_by" name="_order_by">
<?php
foreach ($order_list as $output) :
$selected = ( $output['value'] == $order_by ) ? ' selected = "selected" ' : '';
$option = '<option '.$selected .'value="' . $output['value'];
$option = $option .'">';
$option = $option .$output['label'];
$option = $option .'</option>';
echo $option;
endforeach;
?>
</select>
<p><label><strong><?php _e( 'Order', 'pietergoosen' )?><strong></label></p>
<select id="_asc" name="_asc">
<?php
foreach ($sort as $output) :
$selected = ( $output['value'] == $asc ) ? ' selected = "selected" ' : '';
$option = '<option '.$selected .'value="' . $output['value'];
$option = $option .'">';
$option = $option .$output['label'];
$option = $option .'</option>';
echo $option;
endforeach;
?>
</select>
<p><strong><label><?php _e( 'Posts per Page', 'pageofposts' ); ?><strong></label></p>
<input id="_post_count" name="_post_count" type="text" value="<?php echo $post_count; ?>" size="3" />
<p><strong><label><?php _e( 'Posts in the last days', 'pageofposts' ); ?><strong></label></p>
<input id="_days" name="_days" type="text" value="<?php echo $days; ?>" size="3" />
</div>
<!-- End page of posts meta box -->
<?php
}
function pietergoosen_pop_update_post_meta_box( $post_id ){
if ( empty( $_POST ) ) {
return;
} else {
$template_file = get_post_meta($post_id,'_wp_page_template',TRUE);
if ($template_file != 'page-pop.php') return;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
return $post_id;
} else {
if ( $_POST['post_type'] == 'page' ) {
if ( !current_user_can( 'edit_page', $post_id ) )
return $post_id;
} else {
if ( !current_user_can( 'edit_post', $post_id ) )
return $post_id;
}
$meta = isset( $_POST['_cat_id'] ) ? $_POST['_cat_id'] : 1;
pietergoosen_pop_update_post_meta($post_id, '_cat_id', $meta);
$meta = isset( $_POST['_page_title'] ) ? $_POST['_page_title'] : '';
pietergoosen_pop_update_post_meta($post_id, '_page_title', $meta);
$meta = isset( $_POST['_posts_title'] ) ? $_POST['_posts_title'] : '';
pietergoosen_pop_update_post_meta($post_id, '_posts_title', $meta);
$meta = isset( $_POST['_order_by'] ) ? $_POST['_order_by'] : 'date';
pietergoosen_pop_update_post_meta($post_id, '_order_by', $meta);
$meta = isset( $_POST['_asc'] ) ? $_POST['_asc'] : 'DESC';
pietergoosen_pop_update_post_meta($post_id, '_asc', $meta);
$meta = isset( $_POST['_post_count'] ) ? $_POST['_post_count'] : get_option('posts_per_page');
pietergoosen_pop_update_post_meta($post_id, '_post_count', $meta);
$meta = isset( $_POST['_days'] ) ? $_POST['_days'] : 0;
pietergoosen_pop_update_post_meta($post_id, '_days', $meta);
return;
}
}
}
function pietergoosen_pop_update_post_meta($post_id, $key, $data) {
$post_meta = get_post_meta($post_id, $key, true);
if( $data != '' && $post_meta != $data) {
update_post_meta($post_id, $key, $data);
} elseif ( $post_meta != '' && $data == '' ) {
delete_post_meta($post_id, $key);
}
}
?>
Secondly, the page template. You have to call this template page-pop.php
<?php
/**
* Template Name: Page of Posts
*/
get_header(); ?>
<?php
//See if we have any values
$post_meta=array();
$post_meta = get_post_meta( $post->ID,false );
$catid = isset( $post_meta['_cat_id'] ) ? $post_meta['_cat_id'][0] : 1;
$page_title = isset( $post_meta['_page_title'] ) ? $post_meta['_page_title'][0] : '';
$posts_title = isset( $post_meta['_posts_title'] ) ? $post_meta['_posts_title'][0] : '';
$orderby = isset( $post_meta['_order_by'] ) ? $post_meta['_order_by'][0] : 'date';
$asc = isset( $post_meta['_asc'] ) ? $post_meta['_asc'][0] : 'DESC';
$list_style = isset( $post_meta['_list_style'] ) ? $post_meta['_list_style'][0] : 'default';
$post_count = isset( $post_meta['_post_count'] ) ? $post_meta['_post_count'][0] : get_option('posts_per_page');
if(!$post_count || !is_numeric( $post_count )) $post_count = get_option('posts_per_page');
$days = isset( $post_meta['_days'] ) ? $post_meta['_days'][0] : 0;
if($days && !is_numeric( $days )) $days = 0;
$do_not_show_stickies = ($list_style == 'default') ? 0 : 1;
?>
<div id="main-content" class="main-content">
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<!-- Page Title -->
<?php if( $posts_title ) : ?>
<article id="posts-title">
<header class="entry-header">
<h2 class="entry-title"><?php echo $posts_title; ?></h2>
</header><!-- .entry-header -->
</article><!-- #posts-title -->
<?php endif; ?>
<?php the_post(); ?>
<?php global $post;
if( $post->post_content || $page_title ) : ?>
<div class="entry-content">
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php if( $page_title ) : ?>
<header class="entry-header">
<h1 class="entry-title"><?php echo $page_title; ?></h1>
</header><!-- .entry-header -->
<?php endif; ?>
<?php if( $post->post_content ) : ?>
<div class="entry-content">
<?php the_content(); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'pietergoosen' ) . '</span>', 'after' => '</div>' ) ); ?>
</div><!-- .entry-content -->
<footer class="entry-meta">
</footer><!-- .entry-meta -->
<?php endif; ?>
</article><!-- #post-<?php the_ID(); ?> -->
</div>
<?php endif; ?>
<?php
/* Do we have any category */
global $post;
// Save posts for later use
$tmp_post = $post;
$args = array(
'cat' => $catid,
'posts_per_page' => $post_count,
'paged' => $paged,
'orderby' => $orderby,
'order' => $asc,
'ignore_sticky_posts' => $do_not_show_stickies,
);
if( $days ) {
function pop_filter_where( $where = '') {
global $days;
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-' .$days .' days')) . "'";
return $where;
}
add_filter( 'posts_where', 'pop_filter_where' );
$wp_query= null;
$wp_query = new WP_Query();
$wp_query->query( $args );
remove_filter( 'posts_where', 'pop_filter_where' );
} else {
$wp_query= null;
$wp_query = new WP_Query();
$wp_query->query( $args );
}
// Output
if ( $wp_query->have_posts() ) :
// Start the Loop.
while ( $wp_query->have_posts() ) : $wp_query->the_post();
get_template_part( 'content', get_post_format() );
endwhile;
pietergoosen_pagination();
else :
get_template_part( 'content', 'none' );
endif; ?>
<?php
// Reset the post to the page post
$post = $tmp_post;
?>
<?php if ( comments_open() || get_comments_number() ) {
comments_template();
} ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_sidebar( 'content' ); ?>
</div><!-- #main-content -->
<?php
get_footer();
You can now simply create a new page and choose the "page of posts" template, and publish your page. Once that is done, the Page of Posts metabox will appear. From that you can choose the category to display on that page.
There's a plugin that will do that. http://wordpress.org/plugins/posts-per-cat/
He used the plugin then set it to a ridiculous number so that it would show all the categories on the page. Here's the link to the website I found the answer on:
https://wordpress.stackexchange.com/questions/45856/show-posts-of-category-in-a-page
I hope that helps.

Resources