WordPress.org

Ready to get started?Download WordPress

Forums

$do_not_duplicate and functions.php (3 posts)

  1. notkristina
    Member
    Posted 3 years ago #

    I've got some additional front-page loops being called from my functions.php file via my theme, and they're working great. Only trouble is I don't seem to be able to get my actual main loop template to respect the do_not_duplicate array. This is the code I've got now, which is very wrong somehow:

    In functions.php:

    global $do_not_duplicate;
    $do_not_duplicate = array();
    
    function latest_template($category){
    if (is_front_page() && !is_paged()){
    $temp_query = $wp_query;
    $my_query = new WP_Query('category_name='.$category.'&posts_per_page=4');
    	// Start of 'The Loop'
    	if(have_posts()){
      while ($my_query->have_posts()) : $my_query->the_post();
    		 $do_not_duplicate[] = $post->ID;

    [etc., to the end of the latest_template function]

    In the post loop template:

    global $do_not_duplicate;
    // Start of 'The Loop'
    if (is_front_page()){
    	query_posts(array('post__not_in'=>$do_not_duplicate));
    	}
    
    if(have_posts()){
    while (have_posts()) : the_post();

    All the posts that are getting pulled in by the function in functions.php are also appearing in the loop, even though I have attempted to create a separate query for the front page that will exclude them.

    I'm sure the problem is very elementary, but I'm not very strong in PHP and globals are a little over my head (apparently), so I haven't been able to spot the problem. Can anyone point me in the right direction?

    Thank you!

  2. alchymyth
    Forum Moderator
    Posted 3 years ago #

    you could try to declare the global variable within the function;

    example:

    function latest_template($category){
      global $do_not_duplicate;
      $do_not_duplicate = array();
    if (is_front_page() && !is_paged()){
    .....
  3. notkristina
    Member
    Posted 3 years ago #

    I think I've got it now. I started printing the contents of the array to find that it was always empty. It stopped being empty when I replaced $post->ID with get_the_ID(), and now everything appears to be behaving exactly as it should. I also needed to declare the global array in the function again, so thanks for reminding me, alchymyth!

    I swear I worked on this all day before I finally broke down and posted a question, and then I stopped working on it entirely and somehow stumbled on the solution. Seems to always happen that way.

Topic Closed

This topic has been closed to new replies.

About this Topic