• within a loop i’m retrieving the category slug of a post with this code:

    $category = get_the_category();
    $kat = $category[0]->category_nicename;

    the problem starts when a post belongs to more than one category. wordpress permalinks are made with the category slug that has the lowest cat id. my example seems to return the category slugs alphabetically.

    how can i just get the slug with the lowest id?

Viewing 1 replies (of 1 total)
  • Try this..

    // Create 2 empty arrays
    $c_categories = $t_terms = array();
    // Fill one array with categories
    $c_categories = get_the_category();
    // Check if array is empty, if not we have cats
    if( !empty( $c_categories ) ) {
    	// For each category in the array
    	foreach( $c_categories as $c_category ) {
    		// Place data into the second array using cat/term id as array key value
    		$t_terms[$c_category->term_id] = $c_category;
    		// Unset variable no longer needed
    		unset( $c_category );
    	}
    	// Get the array item with the lowest key
    	$kat = min( $t_terms );
    	// Unset some more variables no longer needed
    	unset( $c_categories , $t_terms );
    	// Finish up and convert the variable to the category nice name
    	$kat = $kat->category_nicename;
    }

    Does that help?

Viewing 1 replies (of 1 total)
  • The topic ‘get the category slug of a post’ is closed to new replies.