How to push/create an associative array? - php

I am running a loop of posts and these have four properties I need to associate: title, date, link, location:
while (have_posts()) : the_post();
if( !in_array( $post->ID, $already_displayed_ids )) {
array_push( $thisPostid, $post->ID );
$title = get_the_title();
$location = usp_get_meta(false, 'usp-custom-8');
$link = get_permalink();
$contentYear = usp_get_meta(false, 'usp-custom-14');
if ($contentYear >= 0 && $contentYear <= 2019) {
array_push($yearsArray, $contentYear);
if (($wp_query->current_post +1) == ($wp_query->post_count)) {
$yearsArray = array_unique($yearsArray);
sort($yearsArray);
}
}
array_push( $already_displayed_ids, $post->ID );
}
endwhile;
Basically I am running a loop, I check for non duplicate in $already_displayed_ids and I need to associate and push the title, location, date and link of any post I am pushing here array_push($yearsArray, $contentYear);
At the moment I am only able to push $contentYear but there is not link, title or location associated to the pushed post, I thought of creating an associative array in order to push all the specs I need of each posts. $contentYear is a custom field with a date, so I am genertaing a navigation with those values, they are dates. But I need to associate to each date their title, location and link as I currently don't know how to push those specs to associated to the time I am pushing.

This is how I resolved it:
while (have_posts()) : the_post();
if( !in_array( $post->ID, $already_displayed_ids )) {
array_push( $thisPostid, $post->ID );
$contentYear = usp_get_meta(false, 'usp-custom-14');
if ($contentYear >= 0 && $contentYear <= 2019) {
array_push($yearsArray,
array(
'year'=> $contentYear,
'link'=> get_permalink(),
'location'=> usp_get_meta(false, 'usp-custom-8'),
'title'=> get_the_title()
)
);
}
array_push( $already_displayed_ids, $post->ID );
}
endwhile;
Then I can do foreach ($yearsArray as $year) { and echo $year['title'] etc

As far as im aware there is no direct functionality for getting an associative array from posts.
Here is a snippet of what your asking for:
$posts = array();
if (have_post()) :
while (have_posts()) :
array_push($posts,
Array(
'id'=>the_ID(),
'quantity'=>1,
'size'=>$size,
'colour'=>$colour
)
);
endwhile;
$_SESSION['cart'] = $posts[0]; // change 0 index
endif;
Please note the above code is not ideal, and you probably should be doing this. Also you may want to be using cookies and not sessions.

Related

How to increment posts within a specific category for every 6 posts of all categories

I am successfully returning a post from the 'CTA' category every 6 posts on the page. However every time the loop is run I get stuck with the first post in the array instead of the incremental progression of all the CTA posts.
I've tried returning the posts by RAND order and that worked better but did have repeats. I don't seem to be able to get the count set for the CTA category after already setting a counter for every six posts.
<?php if ( $query->have_posts() ) { ?>
<?php while ($query->have_posts()) {
if( $query -> post_count > 0 ) {
$postnum = 0;
foreach( $query -> posts as $post ) {
$postnum++;
if( $postnum%5 == 0 ) {
$args = array( 'cat' => 1824, 'posts_per_page' => 1, );
query_posts( $args );
$current_post = 0;
while ( have_posts() ) : the_post();
$current_post++;
echo "CTA Card Specific Info";
endwhile;
}
$query->the_post();
?>

Can I compare a category slug in wordpress to a page title?

I have a structured my blog posts to have categories, and the slugs of these categories are identical to some custom-post post titles.
I want to run a link from the post to the custom-post page using these matching slugs.
In single.php I am trying to run this code... but instead of returning the information of the custom-post it returns the information of the current post
<?php
$categories = get_the_category();
if ( ! empty( $categories ) ) {
foreach( $categories as $category ) {
$current_slug = $category->slug;
$args = array(
'post_type' => 'community',
'name' => $current_slug
);
$cat_query = new WP_Query($args);
if ( $cat_query->have_posts() ) {
the_title( sprintf( '<h3 class="post-title">', esc_url( get_permalink() ) ), '</h3>');
wp_reset_postdata();
}
}
}
?>
My hope for this code was -> if a post is given a category with the slug: 'cat-one' then at the top of the post would be a link to the CAT ONE page (which is a custom post type page with a url ..../communities/cat-one.
This should absolutely be possible. There's a few issues with your code however, and I've cleaned up a few other things.
You've got the code set up to loop through the categories, but you're using name in your WP_Query() args, and don't have a loop set up for the results. According to the WP_Query() docs, name will return a single post - if you want more than one, (since WP 4.4) you can use post_name__in instead. Also, and namely the larger issue with your code, is that you're never set up the internal variables inside your $cat_query. I've also added a while loop so it will spit out multiple category links.
Without defining the internal variables with the $query->the_post() method (or passing a $post_id argument to them), the post variable functions like the_title() and get_permalink() will use the current post, which is what your'e seeing now.
This should get you started:
if( $categories = get_the_category() ){
foreach( $categories as $category ){
$args = array(
'post_type' => 'community',
'post_name__in' => $category->slug
);
$cat_query = new WP_Query( $args );
if( $cat_query->have_posts() ){
while( $cat_query->have_posts() ){
$cat_query->the_post();
the_title( sprintf( '<h3 class="post-title">', esc_url( get_permalink() ) ), '</h3>');
}
wp_reset_postdata();
}
}
}

Sum of all custom fields for category

I've got a custom field on posts called number.
On the front-end in category.php, I need to total up the value of all posts in the current category that have number.
So for example, if the current category had 3 posts, and in each post the number values were 1, 5 and 10 respectively, then on the front-end it needs to display the total 16.
I'm not entirely sure where to start with this.
The loop I have at the moment:
<?php if ( have_posts() ) : ?>
<h1><?php printf( __( 'Category Archives: %s', 'twentythirteen' ), single_cat_title( '', false ) ); ?></h1>
<p></p>
<?php /* The loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
<?php else : ?>
<?php // ?>
<?php endif; ?>
Any help is appreciated.
Thanks everyone. There was a lot there that helped me arrive at this solution (and a little help from Google):
<?php
$args = array(
'numberposts' => -1,
'offset' => 0,
'category' => $category
);
$numbers = get_posts( $args );
$total = 0;
foreach( $numbers as $numbersID ) {
$single = get_post_meta( $numbersID->ID, 'numbers', true );
$total += $single;
}
echo $total;
?>
The key was knowing to increment a variable += as #rnevius suggested, which I didn't know about.
A shorter version of what you're trying to achieve (which also reduces calls to the database) would look something like the following:
<p>
<?php
$total = 0;
foreach( $wp_query->posts as $number ) {
$total += get_post_meta( $number->ID, 'numbers', true );
}
echo $total;
?>
</p>
As mentioned in another comment, you don't need another loop, as your posts already exist in $wp_query.
Supposing you're using MySQL use SUM() Method to achive your goals. Query might look something like SELECT SUM(number) FROM category WHERE [drill down to a specific set of categories if neccesary];

Get post format

I needed to use the category name as a class for the H1, and also needed to exclude category 2. So I botched together the PHP code below. It works fine except the post looses it's formatting. I know that get_post_format() is what applies the format, but when I add it, it doesn't seem to do anything. Any help would be appreciated, thanks.
<?php while ( have_posts() ) : the_post();
$excludedcats = array(2);
$count = 0;
$categories = get_the_category();
foreach($categories as $category)
{
$count++;
if ( !in_array($category->cat_ID, $excludedcats) )
{
echo '<h1 class="category-heading ' . sprintf( __( "heading-%s" ), $category->slug ) . '" >';
if( $count != count($categories) )
{
echo " ";
}
}
}
single_post_title();
echo '</h1>';
the_content();
?>
get_post_format() doesn't apply the format; it just returns the post type, which you can then use to apply the format. In order to have different formats for different post types, you can do something like this:
<?php
get_template_part( 'content', get_post_format() );
?>
And then you need another file, content-[post-type-slug].php (e.g. for image posts, the file would be called content-image.php) where you display the post. You could also just use a switch statement on the return value of get_post_format() but that can get messy.

Return all values stored in var outside foreach loop

So I assume something is being overwritten but I am unsure as to how to stop this and retrieve all values outside loop. Any ideas?
foreach($gallids as $gallterm)
{
$postterms = wp_get_post_terms($gallterm, 'type', array("fields" => "slugs"));
$checkmissing = $postterms[0];
print_r($checkmissing); // Check Terms for missing images - works here.
}
print_r($checkmissing); // Check Terms for missing images - not working here
// - seems to be getting last or first val only.
First of all initialize the variable you want to use later on:
$checkmissing = array();
Then inside the foreach append the first entry of the post terms to that array:
foreach($gallids as $gallterm)
{
list($checkmissing[]) = wp_get_post_terms($gallterm, 'type', array("fields" => "slugs"));
}
See $checkmissing[], that is what effectively will prevent that you overwrite it. It will append each to the array.
Finally you can output the result after the loop:
print_r($checkmissing);
Note: You should do some additional handling if wp_get_post_terms returns an empty array:
foreach($gallids as $gallterm)
{
$terms = wp_get_post_terms($gallterm, 'type', array("fields" => "slugs"))
AND list($checkmissing[]) = $terms
;
}
I tried a few of the examples above and they didn't quite work the way I wanted. So I poked around and did a little research, here's how I got it working for me.
In my particular case I needed to grab all the category ID's for a specific post, then return that variable into the WP_Query arguments array.
First, you will need to grab the post terms
$terms = get_the_terms( $post->ID, 'category' );
Next you'll want to initialize the variable you want to use later on:
$cat_terms = array();
Next you'll declare the foreach to get each individual term ID
foreach ( $terms as $term ) {
$cat_terms[] = $term->term_id;
}
Now let's say you want to use return a comma separated list for this $cat_terms variable. We're going to use the 'join' function
$comma_separated_terms = join( ", ", $cat_terms );
Now let's say you want to use this variable to put into you WP_Query loop for say the 'category__in' parameter. We're going to use 'array_values'.
$values = array_values($cat_terms);
The nice thing about this is now we can insert this $values variable into the WP_Query arguments:
<?php global $post;
$query = new WP_Query(array(
'post_type' => 'post_type_name',
'category__in' => $values));
?>
In my particular case, the client wanted some custom post types to display in the sidebar based on the blog posts categories. So I needed to get all the blog post terms and match them up with the terms for the custom post types categories.
Final Code Looked something like this:
<?php
$terms = get_the_terms( $post->ID, 'category' );
$cat_terms = array();
foreach ( $terms as $term ) {
$cat_terms[] = $term->term_id;
}
$values = array_values($cat_terms);
?>
<h3><?php echo $title; ?></h3>
<?php global $post;
$query = new WP_Query(array(
'post_type' => 'custom_post_type',
'category__in' => $values));
if ( $query->have_posts() ) : ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
// Code for loop goes here
<?php endwhile; endif; ?>
<?php wp_reset_postdata(); ?>
$checkmissing = array();
foreach($gallids as $gallterm)
{
$postterms = wp_get_post_terms($gallterm, 'type', array("fields" => "slugs"));
$checkmissing[] = $postterms[0];
print_r($checkmissing); // Check Terms for missing images - works here.
}
print_r($checkmissing); // Check Terms for missing images
// will get all missing images as array
foreach($gallids as $gallterm) {
$postterms = wp_get_post_terms( $gallterm, 'type', array("fields" => "slugs") );
$checkmissing[] = $postterms[0];
}
print_r($checkmissing); //Now this will be a 2d array with all your values..
$checkmissing = array();
$i=1;
foreach($gallids as $gallterm)
{
$postterms = wp_get_post_terms($gallterm, 'type', array("fields" => "slugs"));
$checkmissing[$i] = $postterms[0];
//print_r($checkmissing); // Check Terms for missing images - works here.
$i++;
}
print_r($checkmissing);

Categories