WordPress.org

Ready to get started?Download WordPress

Forums

Next/Prev_post_link doesn't exclude more than 1 cat (3 posts)

  1. nocitizen
    Member
    Posted 7 years ago #

    This is the code I've placed within the loop:

    <div id="postnav">

    <p class="prevpost">
    <?php previous_post_link('« %link','Last', FALSE, '1 and 6 and 25 and 28'); ?>

    <p class="nextpost">
    <?php next_post_link('%link »', 'Next', FALSE, '1'); ?>

    </div>

    I want to exclude categories 1, 6, 25, and 28 for both the previous and next links. Given the code above, the next link excludes posts from cat 1, the link for prev cat doesn't exclude anything. Why? (I excluded cat 1 in the next link in the code above for demonstration purpose only, that is, to show that one excluded category works, but trying to exclude multiple cats doesn't.)

    'Preciate any help, thanks -Lee

  2. TristanSept
    Member
    Posted 7 years ago #

    I recently experienced the same problem and I decided to have a look inside WP and fix it by myself.

    That's a bug in the link-template.php file. Basically, just a missing dot and a mismatch of variables.

    You can easily patch it yourself : in the file wordpress/wp-includes/link-template.php, locate "function get_previous_post" (and its counterpart, "function get_next_post").

    Now, in both functions, replace the following part of the code... (Note that this code may slightly differ from one version of WP to another.)

    $sql_exclude_cats = '';
    	if ( !empty($excluded_categories) ) {
    		$blah = explode(' and ', $excluded_categories);
    		foreach ( $blah as $category ) {
    			$category = intval($category);
    			$sql_cat_ids = " OR pc.category_ID = '$category'";
    		}
    		$posts_in_ex_cats = $wpdb->get_col("SELECT p.ID from $wpdb->posts p LEFT JOIN $wpdb->post2cat pc ON pc.post_id = p.ID WHERE 1 = 0 $sql_cat_ids GROUP BY p.ID");
    		$posts_in_ex_cats_sql = 'AND ID NOT IN (' . implode($posts_in_ex_cats, ',') . ')';
    	}

    ... with these lines :

    $sql_exclude_cats = '';
    	if ( !empty($excluded_categories) ) {
    		$blah = explode(' and ', $excluded_categories);
    		foreach ( $blah as $category ) {
    			$category = intval($category);
    			$sql_exclude_cats .= " OR pc.category_ID = '$category'";
    		}
    		$posts_in_ex_cats = $wpdb->get_col("SELECT p.ID FROM $wpdb->posts p LEFT JOIN $wpdb->post2cat pc ON pc.post_id=p.ID WHERE 1 = 0 $sql_exclude_cats GROUP BY p.ID");
    		$posts_in_ex_cats_sql = 'AND ID NOT IN (' . implode($posts_in_ex_cats, ',') . ')';
    	}

    Hope that it will be useful and that this bug will be fixed in the next release of WP.

  3. rembem
    Member
    Posted 7 years ago #

    thank you so much for this fix. I wrestled this issue for hours.

Topic Closed

This topic has been closed to new replies.

About this Topic