简体   繁体   中英

Wordpress - Using variables from 'header.php' in 'index.php' to exclude posts from query

In 'header.php' I have a post query for a section called "Featured Posts". In that query I defined a variable called "ids". I want to use it in the loop from 'index.php' with 'post__not_in' so this posts from the "Featured Posts" section will not show in the post query from 'index.php". But I'm getting an error like "Undefined variable: ids". How can I use that variable from 'header.php' in 'index.php'?

This is what I have so far:

  <!-- HEADER.PHP --> <?php $custom_query_args = array( 'post_type' => array( 'post', 'reviews'), 'meta_key' => '_is_ns_featured_post', 'meta_value' => 'yes', 'posts_per_page' => '3', 'showposts' => '3' ); $custom_query_args['paged'] = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1; $custom_query = new WP_Query( $custom_query_args ); ?> <?php // Pagination fix global $wp_query; $temp_query = $wp_query; $wp_query = NULL; $wp_query = $custom_query; $ids = array(); ?> <!-- INDEX.PHP: --> <?php $args = array( 'post_type' => array( 'post', 'reviews'), 'posts_per_page'=> 10, 'post__not_in' => $ids ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?> 

There are a few different approaches you can follow to solve this issue. The use of a global variable is how a couple of the top selling premium themes do it.

1) Use a global variable.

In header.php :

$ids = array(1,3,5,7,9);
global $my_globals;
$my_globals['ids'] = $ids;

In index.php :

global $my_globals;
$ids = $my_globals['ids'];

See #3 below for why some WordPress programmers say using global is not optimal.

2) Create a function that creates and then returns the $ids array. Run the function both in header.php and index.php / Disadvantage here is overworking the mysql on a low end server resulting in slow page load.

3) Another solution would be to use cache to hold the array between the two pages. The approach is explained very clearly here, so it would be easier to just go and see it here https://wordpress.stackexchange.com/a/89271/19155 ... along with a bunch of reasons as to why using global is considered by some to be an incorrect approach.

4) Use the 'NS Featured Posts' plugin, (4.7/5 rating, ~2000 downloads) which contains the functionality you seek. https://wordpress.org/plugins/ns-featured-posts/

The use of the $globals should do this..

   $args = array(
       'post_type' => array( 'post', 'reviews'),
       'posts_per_page'=> 10,
        'post__not_in' => $GLOBALS['ids']
   );

In your header.php

   $GLOBALS['ids']= array();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM