Wordpress: exclude category - wordpress

I want to exclude a category from my homepage, but my code didn't work:
<?php if( $category_items_query->have_posts() ): ?>
<div class="row columns-layout content-grid">
<?php if( $layout === 'two' ): ?>
<!-- EXCLUDE CATEGORY 17 -->
<?php query_posts($query_string . '&cat=-17'); ?>
<?php while( $category_items_query->have_posts() ): $category_items_query->the_post(); ?>
<div class="col-lg-6 col-md-6 recent-item two-columns post-box">
<?php get_template_part( 'parts/home-content', 'columns' ); ?>
</div><!-- .two-columns -->
<?php endwhile; ?>
<?php endif; ?>
</div><!-- .row -->
<?php endif; ?>
Please help me.
Thanks
Guido

Please do not use query_posts as it is ineffiecnt and re-run sql queries and will also mess up your pagination..
Instead use pre_get_posts e.g.
function exclude_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'cat', '-17' );
}
}
add_action( 'pre_get_posts', 'exclude_category' );

First you must define global variable like below , then you can try your code.
global $query_string;
query_posts($query_string . '&cat=-17');
Also there is another way that you can try as well :
In function.php :
function exclude_category( $wp_query ) {
$excluded = array( '-1' );
$wp_query->set('category__not_in', $excluded);
set_query_var( 'category__not_in', $excluded );
}
add_action( 'pre_get_posts', 'demo_exclude_category' );
In your code (you can use in your way) :
class Exclude_Cat_Plugin {
public function __construct() {
add_action( 'pre_get_posts', array( $this,'exclude_first_category_posts') );
}
public function exclude_first_category_posts( $wp_query ) {
if ( ! is_search() && ! is_archive() ) {
$excluded = array( '-1' );
$wp_query->set( 'category__not_in', $excluded );
set_query_var( 'category__not_in', $excluded );
}
}
}
I hope its help you.

Related

Sorting custom post types depends on ACF Date Field

My task is to sort all the custom post types ('audio', 'video', 'webdev' etc.) gathered by taxonomy 'portfolio' or by any tag. And I do it with following code.
add_filter( 'pre_get_posts', 'custom_post_types_sort' );
function custom_post_types_sort( $query ) {
if ( is_tax('portfolio') || is_tag() ) {
$cptui_post_types = cptui_get_post_type_slugs();
// Sort portfolio taxonomy posts by project start date.
$query->set( 'post_type', $cptui_post_types );
$query->set( 'order', 'DESC' );
$query->set( 'orderby', 'meta_value_num' );
$query->set( 'meta_key', 'date' );
}
}
?>
Everything works fine except one thing. My menu not showing on the taxonomy template. I'm using taxonomy-portfolio.php template to display pages.
I assume this is happening because of query modification.
<?php
/**
* Portfolio Taxonomy Template
*/
get_header();
?>
<section class="portfolio-template swiper">
<div class="swiper-wrapper postfolio-list">
<div class="swiper-slide">
<?php get_template_part( 'template-parts/breadcrumbs' ); ?>
<div class="portfolio-project-items">
<?php if ( have_posts() ) : ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'template-parts/content', 'portfolio-item' ); ?>
<?php endwhile; ?>
<?php endif; ?>
</div>
</div>
</div>
</section>
<?php get_footer(); ?>
Replace this
if ( is_tax('portfolio') || is_tag() ) {
by this
if ( ( is_tax('portfolio') || is_tag() ) && $query->is_main_query() ) {
Check the docs: https://developer.wordpress.org/reference/functions/is_main_query/
This function is most commonly used within hooks to distinguish
WordPress’ main query (for a page, post, or archive) from a
custom/secondary query.
Does this fix your problem?

Show Sticky Posts at the top but do not show these posts again in the loop?

Regarding wordpress.org
For the main loop on my homepage I want to display the sticky posts at the top BUT I don't want the post to appear again in the loop, otherwise it appears redundant to the visitor.
Problem with the below code is they remove the sticky post from the top.
I want to KEEP the sticky posts at the top
but REMOVE/EXCLUDE it from the loop. Is this possible?
CODE A: This removes sticky post from top
function mango($query){
if ( $query->is_home() && $query->is_main_query() && !is_admin() ) {
$query->set( 'ignore_sticky_posts', true );
}
}
add_action( 'pre_get_posts', 'mango' );
CODE B: This removes sticky post from both the top AND loop
function mango($query){
if ( $query->is_home() && $query->is_main_query() && !is_admin() ) {
$query->set( 'post__not_in', get_option( 'sticky_posts' ) );
}
}
add_action( 'pre_get_posts', 'mango' );
I think that you must create two loops for this. One for sticky posts and one for regular ones (but exclude sticky posts from second loop). Obviously you must put this code into index.php. Didn't test it but I think it should do the trick...
<?php //we will get "Sticky Posts" only with this loop
$sticky = get_option( 'sticky_posts' );
$args = array(
/* Add whatever you need here - see http://codex.wordpress.org/Class_Reference/WP_Query */
'post__in' => $sticky,
);
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query( $args );
if ( $wp_query->have_posts() ) : ?>
<?php while ( $wp_query->have_posts() ) : $wp_query->the_post();
if ( empty( $sticky ) ) break;
?>
<?php
$wp_query = null;
$wp_query = $temp;
wp_reset_query();
?>
<?php endwhile; ?>
<?php endif; ?><!--END if THE LOOP-->
<?php //Exlude stickies from second loop...
$sticky = get_option( 'sticky_posts' );
$args = array(
'post__not_in' => $sticky,
);
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query( $args );
if ( $wp_query->have_posts() ) : ?>
<?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
<?php endwhile; ?>
<?php endif; ?><!--END if THE LOOP-->
<?php
$wp_query = null;
$wp_query = $temp;
wp_reset_query();
?>

Shortcode displaying shortcode and not content

Im using "insert pages" plugin for wordpress that allows me to insert pages and posts into other pages and posts from the backend. My problem being that when i i use "insert pages" plugin in my news section and then visit the site it shows the shortcode instead of the content. This seems to be a problem only when making a "post". If i use the plugin to display a page within another page it works fine (shows the content not the shortcode).
Any idea what could be the cause of this problem?
Cheers,
Emil
Update
// Shortcode hook: Replace the [insert ...] shortcode with the inserted page's content
function insertPages_handleShortcode_insert( $atts, $content = null ) {
global $wp_query, $post, $wp_current_filter;
extract( shortcode_atts( array(
'page' => '0',
'display' => 'all',
), $atts ) );
// Validation checks.
if ( $page === '0' ) {
return $content;
}
// Trying to embed same page in itself.
if ( $page == $post->ID || $page == $post->post_name ) {
return $content;
}
// Don't allow inserted pages to be added to the_content more than once (prevent infinite loops).
$done = false;
foreach ( $wp_current_filter as $filter ) {
if ( 'the_content' == $filter ) {
if ( $done ) {
return $content;
} else {
$done = true;
}
}
}
// Get page object from slug or id
$temp_query = clone $wp_query; // we're starting a new loop within the main loop, so save the main query
$temp_post = $wp_query->get_queried_object(); // see: http://codex.wordpress.org/The_Loop#Multiple_Loops_Example_2
// Convert slugs to page IDs to standardize query_posts() lookup below.
if ( ! is_numeric( $page ) ) {
$page_object = get_page_by_path( $page, OBJECT, get_post_types() );
$page = $page_object ? $page_object->ID : $page;
}
if ( is_numeric( $page ) ) {
$args = array(
'p' => intval( $page ),
'post_type' => get_post_types(),
);
} else {
$args = array(
'name' => esc_attr( $page ),
'post_type' => get_post_types(),
);
}
query_posts( $args );
// Start our new Loop
while ( have_posts() ) {
ob_start(); // Start output buffering so we can save the output to string
// Show either the title, link, content, everything, or everything via a custom template
// Note: if the sharing_display filter exists, it means Jetpack is installed and Sharing is enabled;
// This plugin conflicts with Sharing, because Sharing assumes the_content and the_excerpt filters
// are only getting called once. The fix here is to disable processing of filters on the_content in
// the inserted page. #see https://codex.wordpress.org/Function_Reference/the_content#Alternative_Usage
switch ( $display ) {
case "title":
the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php break;
case "link":
the_post(); ?>
<?php the_title(); ?>
<?php break;
case "excerpt":
the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php if ( has_filter( 'the_content', 'sharing_display' ) ) echo get_the_excerpt(); else the_excerpt(); ?>
<?php break;
case "excerpt-only":
the_post(); ?>
<?php if ( has_filter( 'the_content', 'sharing_display' ) ) echo get_the_excerpt(); else the_excerpt(); ?>
<?php break;
case "content":
the_post(); ?>
<?php if ( has_filter( 'the_content', 'sharing_display' ) ) echo get_the_content(); else the_content(); ?>
<?php break;
case "all":
the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php if ( has_filter( 'the_content', 'sharing_display' ) ) echo get_the_content(); else the_content(); ?>
<?php the_meta(); ?>
<?php break;
default: // display is either invalid, or contains a template file to use
$template = locate_template( $display );
if ( strlen( $template ) > 0 ) {
include $template; // execute the template code
} else { // Couldn't find template, so fall back to printing a link to the page.
the_post(); ?>
<?php the_title(); ?><?php
}
break;
}
$content = ob_get_contents(); // Save off output buffer
ob_end_clean(); // End output buffering
}
wp_reset_postdata();
$wp_query = clone $temp_query; // Restore main Loop's wp_query
$post = $temp_post;
$content = "<div data-post-id='$page' id='insertPages_Content'>$content</div>";
return $content;
//return do_shortcode($content); // careful: watch for infinite loops with nested inserts
}
This is could be work for you.
while ( have_posts() ) {
ob_start(); // Start output buffering so we can save the output to string
// Show either the title, link, content, everything, or everything via a custom template
// Note: if the sharing_display filter exists, it means Jetpack is installed and Sharing is enabled;
// This plugin conflicts with Sharing, because Sharing assumes the_content and the_excerpt filters
// are only getting called once. The fix here is to disable processing of filters on the_content in
// the inserted page. #see https://codex.wordpress.org/Function_Reference/the_content#Alternative_Usage
switch ( $display ) {
case "title":
the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php break;
case "link":
the_post(); ?>
<?php the_title(); ?>
<?php break;
case "excerpt":
the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php if ( has_filter( 'the_content', 'sharing_display' ) ) echo get_the_excerpt(); else the_excerpt(); ?>
<?php break;
case "excerpt-only":
the_post(); ?>
<?php if ( has_filter( 'the_content', 'sharing_display' ) ) echo get_the_excerpt(); else the_excerpt(); ?>
<?php break;
case "content":
the_post(); ?>
<?php if ( has_filter( 'the_content', 'sharing_display' ) ) echo do_shortcode( get_the_content() ); else the_content(); ?>
<?php break;
case "all":
the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php if ( has_filter( 'the_content', 'sharing_display' ) ) echo do_shortcode( get_the_content() ); else the_content(); ?>
<?php the_meta(); ?>
<?php break;
default: // display is either invalid, or contains a template file to use
$template = locate_template( $display );
if ( strlen( $template ) > 0 ) {
include $template; // execute the template code
} else { // Couldn't find template, so fall back to printing a link to the page.
the_post(); ?>
<?php the_title(); ?><?php
}
break;
}

wordpress sorting using array merge by price in ascending order but price with 0 must be show last

I'm using below code to filter the query on page and sort the post in ascending order by price. I'm getting desire output but my concern is , i want all price with 0 at last.
<?php
global $wp_query;
$args = array_merge( $wp_query->query_vars, array( 'orderby' => 'meta_value_num','meta_key' => 'price','order' => 'ASC'));
query_posts( $args );
?>
please help me guys...Thanks in advance
full code here:
<?php
/**
* The template for displaying Archive pages.
*
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* #package progression
*/
get_header('cars'); ?>
<?php get_template_part( 'page', 'vehicle-title' ); ?>
<div class="width-container">
<?php if ( have_posts() ) : ?>
<div id="page-title">
<h1 id="page-heading">
<?php if (is_tax('vehicle_type')) {
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
$tax_term_breadcrumb_taxonomy_slug = $term->taxonomy;
echo '' . $term->name . '';
}
?>
</h1>
</div><!-- close #page-title -->
<div id="4-content-container" class="tax-vehicle-container">
<?php echo do_shortcode('[vehicle_searchform include="make,model"]') ?>
<?php
global $wp_query;
$args = array_merge( $wp_query->query_vars, array( 'orderby' => 'meta_value_num','meta_key' => 'price','order' => 'ASC'));
query_posts( $args );
?>
<?php
/* Start the Loop */
$count = 1;
$count_2 = 1;
?>
<?php while ( have_posts() ) : the_post();
if($count >= 5) { $count = 1; }
?>
<div class="grid4column-progression <?php if($count == 4): echo ' lastcolumn-progression'; endif; ?>">
<?php
get_template_part( 'content', 'vehicle');
?>
</div>
<?php if($count == 4): ?><div class="clearfix"></div><?php endif; ?>
<?php $count ++; $count_2++; endwhile; ?>
<div class="clearfix"></div>
<?php show_pagination_links( ); ?>
</div><!-- close #content-container -->
<?php else : ?>
<?php get_template_part( 'no-results', 'inventory' ); ?>
</div><!-- close #content-container -->
<?php endif; ?>
<?php get_sidebar( 'vehicle' ); ?>
</div><!-- close .width-container -->
<?php get_footer(); ?>
If you've got a small number of posts, the quick and dirty thing to do would be to traverse the loop twice, suppressing zeros on the first pass and suppressing everything except zeros on the second pass:
for ($i=0, $i++, $i<=1) :
while (have_posts()) : the_post();
$show_non_zeros = ($i === 0) && ( get_post_meta( get_the_ID(), 'price', true) > 0);
$show_zero_price = ($i === 1) && ( get_post_meta( get_the_ID(), 'price', true) == 0);
if ($show_non_zeros || $show_zero_price) {
//write output
}
end while;
end for;
If you're looking for a faster / more elegant solution, you can usort() $posts between your call to query_posts and the loop.
hope this will be useful to someone.. i done this way
<?php
/* ADDED by for sorting ASCENDING order but call for price(ie price with 0) last */
function my_sort_custom( $orderby, $query ){
global $wpdb;
$orderby = " case when CAST(meta_value AS SIGNED) = '0' then 1 else 0 end ,CAST(meta_value AS SIGNED) ";
return $orderby;
}
add_filter('posts_orderby','my_sort_custom',10,2);
global $wp_query;
$args = array_merge( $wp_query->query_vars, array('meta_key' => 'price'));
query_posts( $args );
?>

How to loop posts from a specific category in WordPress homepage

If I want to loop 3 posts from a specific category in index.php of WordPress than what I've to do?
<?php if ( have_posts() ) : ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
get_template_part( 'content', get_post_format() );
?>
<?php endwhile; ?>
<?php the_posts_navigation(); ?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>
I want to loop 3 post from a category before <?php get_template_part( 'content', 'none' ); ?>
Try this one
$args = array(
'cat' => <your category ID>,
'posts_per_page' => 3
);
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
// ## write your code here..
}
}
You have to put the category ID.
If you have the category name, then use this:
$args = array(
'category_name' =>
);
For more information check this out:
http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters
You can make use of pre_get_posts to alter the main query to get 3 posts from a specific category in the homepage. Add the following to functions.php and be sure to add the category id in the appropriate place
add_action( 'pre_get_posts', function ( $q ) {
if( $q->is_home() && $q->is_main_query() ) {
$q->set( 'cat', CATEGORY_ID );
$q->set( 'posts_per_page', 3 );
}
});

Resources