sectioning content within a wordpress page - wordpress

Building a wordpress site that needs to organize content by stream - e.g Mechanical, Electrical etc. Also, each page needs sections like News, Articles events etc. If you pick one page (say Mechanical) it has to have the following sections
News
Articles (category:articles)
Events (category:events)
The other streams will have the same sections as well
Is there a plugin for achieving or would I be better off building a template page for each vertical and writing php code? Shown code for a page with a single section.
<?php
$args = array(
'posts_per_page' => 1,
'category_name' => 'news',
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'suppress_filters' => true
);
$posts_array = get_posts( $args );
$the_query = new WP_Query($args);
//EXAMPLE NEWS SECTION
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
the_content();
echo $content;
}
} else {
// no posts found
}
?>

In my opinion you could just write a plugin which does that filtering.
Said plugin would have some kind on shortcode that would take a parameter (category for instance) and would return or echo all the posts associated with that category.
Shortcode registration :
add_action('init','register_shortcode');
function register_shortcode(){
add_shortcode('shortcode_name', 'shortcode_function');
}
Shortcode function:
function shortcode_function($attr){
$attr = shortcode_atts(array('category' => 'default'),$attr); //Setting defaults parameters
$args = array(
'category_name' => $attr['category'],
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'suppress_filters' => true
);
$the_query = new WP_Query($args);
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
//echo other html related stuff
the_title();
the_content();
}
}
}
Usage
[shortcode_name category='news']
[shortcode_name] //category defaults at 'default'
In your case a page could be something like that
<div>
News : <br/>
[shortcode_name category='news']
</div>
<div>
Articles : <br/>
[shortcode_name category='articles']
</div>
<div>
Events : <br/>
[shortcode_name category='events']
</div>

I don't think there is one right way to do this... it depends on the scenario... How many posts, how often do sections or "main streams" get added / change, do you need other stuff on the pages etc.
One pretty simple and easily maintained solution would be to:
1. Add mechanical, electrical, etc. as categories alongside news, articles and events
2. Modify (or add) category.php to repeat the loop three times, and only display the posts that belong to each section (other category):
//Loop your sections
foreach(array('news', 'articles', 'events') as $category) {
echo '<h2>' . $category . '</h2>';
//Loop posts
while ( have_posts() ) {
the_post();
//Check if post is in section (by slug!)
if ( in_category($category) ) {
the_title();
the_content();
}
}
//Start the loop over
rewind_posts();
}
Now just assign each post to one (or more) "parents", fx mechanical, and also to one (and only one) of news, articles or events...
If you go to the archive page of mechanical you get three sections
if you go to news you get all news (but also two empty sections, so you should of course check for that).
Note that this could be done using tags or even a custom taxonomy if you wanted, you'd just need to edit a different theme file - see the template hierarchy.
Beware though that this will not work very nicely with pagination, so if that is a concern you will need to deal with that.

Related

WordPress: All posts are rendering instead of rendering only assigned taxonomy posts on taxonomy page

I have a products post type and it has a various categories. Currently there are around fifty plus posts assigned to different categories. Note: I am using a custom taxonomy called product_categories.
Scenario:
I have a category named food-products and it has a sub categories as chocolates, dairy, grocery.
Now when user goes to the category page eg site.com/product-category/food-products at that time all other categories posts are also displaying but when i click on the sub category tabbing menu at that time it displays the correct assigned sub category posts
So, my question is how can the only the respected category of subcategory posts will be displayed on page load ?
<?php $loop = new WP_Query(array('post_type' => 'product', 'posts_per_page' => -1));
$count =0; ?>
<div class="row portfolio-container">
<?php if ( $loop ) : while ( $loop->have_posts() ) : $loop->the_post();
$url = get_the_post_thumbnail_url( $post_id, 'thumbnail_size' );
$terms = get_the_terms( $post->ID, 'product_categories' );
if ( $terms && ! is_wp_error( $terms ) ) :
$links = array();
foreach ( $terms as $term ) { $links[] = $term->name; }
$links = str_replace(' ', '-', $links);
$tax = join( " ", $links );
else :
$tax = '';
endif; ?>
<div class="col-lg-4 col-md-6 portfolio-item <?php echo strtolower($tax); ?>">
<div class="portfolio-wrap">
<img src="<?php echo $url;?>" class="img-fluid" alt="">
<div class="portfolio-info">
<h4><?php the_title();?></h4>
<div class="portfolio-links">
<i class="ion ion-eye"></i>
<i class="ion ion-android-open"></i>
</div>
</div>
</div>
</div>
<?php endwhile;?>
<?php wp_reset_query();?>
<?php endif;?>
</div>
JQuery:
$(window).on('load', function () {
var portfolioIsotope = $('.portfolio-container').isotope({
itemSelector: '.portfolio-item'
});
$('#portfolio-flters li').on( 'click', function() {
$("#portfolio-flters li").removeClass('filter-active');
$(this).addClass('filter-active');
portfolioIsotope.isotope({ filter: $(this).data('filter') });
});
});
Here is my working demo video for review.
Your WP_Query is returning all products, so that is why they are all getting shown on page load. You need to change the query so it only gets the ones in the category/categories you want.
You want to get products in a certain category, e.g. food-products and all it's sub categories, (e.g. chocolates).
To do this, you can change your WP_Query to specify the category to use like this :
$loop = new WP_Query(
array('post_type' => 'product',
'posts_per_page' => -1,
array( 'category_name' => 'food-products' ) // <-- THIS!! Also note that it is in an array
));
This tells WP_Query to get all product posts that belong to the food-products category, so it will return any products with the food-products category as well as any products in any of the child categories, e.g. chocolates
WP_Query has a number of different ways you can query by category... take a look at the category section of the WP_Query documentation for more information.
UPDATE: Custom Taxonomies
You can do the same thing for custom taxonomies, but you need to use tax_query in the arguments instead of category_name. Your WP_Query should be something like this:
// you don't need to create a variable for the args, if just makes it clearer in the example
$args = array (
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array( // note the nested arrays
'taxonomy' => 'product_categories', // this is the name of your custom taxonomy
'field' => 'slug', // you can search by slug, name, term_id or term_taxonomy_id
'terms' => 'food-products' // the taxonomy slug to search for
)
)
);
$loop = new WP_Query($args);
You might need to change the values for taxonomy and term to match your custom taxonomy. I've also assumed you are searching by slug, but you can search by name or id either.
There is an include_children parameter for the tax_query that you use to say whether or not to include children (e.g. chocolates) in the results, but this defaults to true so you only need to use it if you don't want to include children.
Here's the taxonomy section of the WP_Query documentation for more information.
UPDATE 2: Getting the products for the current category
You say in the comments that you have one template for all of the terms taxonomy-product_categories.php, each category shows in its own page using this template but you only want to show the products with the current term.
What you need to do is use just the current term in the WP_Query, not all of them. You should be able to use get_queried_object() to get the current term and use it in your tax_query instead of hard coding the specific terms.
// get the term of the current page
// We can then use $currentterm->slug in tax_query to dynamically search for this term instead of hard coding a specific term
$currentterm = get_queried_object();
$args = array (
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array( // note the nested arrays
'taxonomy' => 'product_categories', // this is the name of your custom taxonomy
'field' => 'slug', // you can search by slug, name, term_id or term_taxonomy_id
'terms' => $currentterm->slug // search for the slug of the current term
)
)
);
$loop = new WP_Query($args);
So what this should do is: if you are on e.g. site.com/product-category/food-products, it will get the current term which is food-products and then only search for products with that category.
When you go to e.g. site.com/product-category/home-decor, it will dynamically pick up the new term as home-decor and use it in the query.

Wordpress search term pagination broken

I'm having an issue with the pagination in search archives. For some reason whenever I try going to the next page the pagination gives me a 404.
It's a default if (have_posts()) : while (have_posts()) : the_post(); loop.
I don't know how, but I think the reason is because I'm getting redirected to a new page that get's generated somehow. Say I search for stoff. Instead of /page/2/?s=stoff it replaces it with ?attachment_id=550&s=stoff.
Here's what I've tried to do (with no different results)
Change the search query (attachment_id is the same here as well)
Change pagination functions (pagenavi, get_next_posts_link, custom function)
Replacing loop content with just a title
removing header, sidebars, footer
resetting post data
Resetting permalinks (pretty)
You can test the pagination live here (dev location)
Any thoughts on this are greatly appreciated :)
EDIT -
Added Pagination code currently used in search.php
I don't think it should be a problem with the pagination, seeing that I've tried so many different ones, and this pagination still works in every other location at the site, but here it is:
// Numeric Page Navi (built into the theme by default)
function bones_page_navi() {
global $wp_query;
$bignum = 999999999;
if ( $wp_query->max_num_pages <= 1 )
return;
echo '<nav class="pagination">';
echo paginate_links( array(
'base' => str_replace( $bignum, '%#%', html_entity_decode( get_pagenum_link($bignum) ) ),
'format' => '',
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages,
'prev_text' => '←',
'next_text' => '→',
'type' => 'list',
'end_size' => 3,
'mid_size' => 3
) );
echo '</nav>';
} /* end page navi */
The function get's called after the endwhile;

Wordpress Custom Post Types and fields

I have two custom post types…
BOOK and BOOK AUTHOR.
I want to…
LIST all BOOK's by an author on their respective AUTHOR PAGE.
So if i have 10 books by Stephen KING. I want to list them all (and only those by him) on the STEPHEN KING page. I am having real trouble working out how to query posts to do this.
Any advice? I am using advanced custom fields plugin if that helps, but can't work out how to query and display this post information.
I currently use the following code to display ALL of my releases, but how do i get the specific ones on their specific author pages?
<?php
$args=array(
'post_type' => 'book',
'post_status' => 'publish',
'posts_per_page' => 12,
'caller_get_posts'=> 1,
'orderby'=> 'date',
'order' => 'DESC'
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo '';
$i = 0;
while ($my_query->have_posts()) : $my_query->the_post();
if($i % 6 == 0) { ?>
<div class="row">
<?php
}
?>
<img src="<?php the_field('cover_image'); ?>" /><br />
<?php the_field('author_name'); ?><br />
<?php the_title(); ?><br />
</div>
<?php
if($i % 6 == 0) { ?>
<?php
}
$i++;
endwhile;
}
wp_reset_query();
?>
I did something similar, but...
main problem here is, how are you categorizing those books? Did you create taxonomies for that? And those taxonomies are in fact author´s names? I mean, how you sincronize to tell a book belong to certain author?
That is the trick. And then you can just query by category. In this case category must be same slug than author page slug. You will use that data to query post.
What i did in my case is create a function that once an author page is created, a taxonomt with same name and slug is created. So you dont need to manualy create those two things with same name and slug. Something like:
<?php$myposts = get_posts(array(    'showposts' => -1,     'post_type' => 'books',     'tax_query' => array(        array(        'taxonomy' => 'author_book',         'field' => 'slug',         'terms' => array(AUTHOR_SLUG));    )));
notice AUTHOR_SLUG could be an array, like "pete","paul".
"author_book" is just the taxonomy slug. In your case must be just "category_cat"
You can use those args with yout loop.

Let users sort posts in Wordpress

I’d like to create a page for filtering posts based on a number of criteria.
I can work with wp_query and deliver posts quite easily, my problem is that I can’t figure out (nor can I find any answers online about this, believe me I looked) how to let users do this.
Take this for example, returns the posts in order of price (custom field meta value) from highest to lowest with 33 posts.
<?php
$featuredPosts = new WP_Query( array(
'posts_per_page' => 33,
'meta_key'=>'Price',
'orderby' => 'meta_value_num',
'order' => DESC
) );
?>
<?php if ( $featuredPosts->have_posts() ) : ?>
<?php while ( $featuredPosts->have_posts() ) : $featuredPosts->the_post(); ?>
<article <?php post_class('item-post block'); ?> id="post-<?php the_ID(); ?>">
<h2 class="price-title"><?php the_title(); ?> </h2>
</article> <!-- end div post -->
<?php endwhile; wp_reset_query(); ?>
<?php endif; ?>
Now, even after reading and googling, I’ll be damned if I can figure out how I’d implement this on the front end for users to filter posts.
I mean, I know you can append to the URLs in Wordpress to alter the order of posts, but in this context I’m totally lost.
I tried this, but it doesn't work.
<?php
$by_price = esc_url(add_query_arg(array(
'meta_key' => 'price',
'orderby' => 'meta_value_num',
'order' => ASC
)));
$by_date = esc_url(add_query_arg(array(
'orderby' => 'date',
'order' => DESC
)));
?>
<ul>
<li>Order by price</li>
<li>Order by date</li>
</ul>
What I’m trying to achieve is actually quite simple as well, let the user choose the category, choose the price range (guessing I’d write something in JQuery to deliver a value into an field), set the number of results they’d like to be returned.
I’ve tried googling everything under the sun I can think of for this, no dice.
Try Simple Custom Post Order plugin.
It is using AJAX and JavaScript, you don’t have to load anything else. You have to just drag and drop the posts.
OK, I update the code to make it clear:
---I do not think meta_key would be auto-pickup---
functions.php
...
$whitList = array(
'price' => array(
'posts_per_page' => 33,
'meta_key'=>'price',
'orderby'=>'meta_value_num',
'order' => ASC
),
'date' => array(
'posts_per_page' => 33,
'orderby'=>'date',
'order' => DESC
)
);
...
Your first loop php:
<?php
gloabl $whitList; //to use the $whitList in your functions.php.
$aryQuery = $whitList[$_REQUEST['orderby']] ? $whitList[$_REQUEST['orderby']] : $whitList['price'];
$featuredPosts = new WP_Query( $aryQuery );
....
....
?>
For your list page:
<ul>
<?php
gloabl $whitList; //to use the $whitList in your functions.php.
foreach( $whitList as $orderby => $aryOrderBySettings){
?>
<li> Order by <?php echo $orderby;?></li>
<?php
}
?>
</ul>
Using $_GET parameters is the way to go here. First of all you'll want to allow your visitors access to these add these variables. The link approach is fine, overall, so we can generate augmented links by using the add_query_arg to tack on extra parameters to the current URL.
<?php
$urla = add_query_arg( 'sort' => 'price', 'asc' => '1' );
$urld = add_query_arg( 'sort' => 'price', 'asc' => '0' );
?>
Sort by price (asc)
Sort by price (desc)
When clicked, the tacked on variables can thus be detected:
<?php
// Get an allowed sort variable and the order
$sort = isset( $_GET['sort'] ) && in_array( $_GET['sort'], array( 'price' ) ) )
? $_GET['sort'] : null;
$order = isset( $_GET['asc'] ) && $_GET['asc'] == '0' ? 'DESC' : 'ASC';
?>
Now you would augment your main query with the data you just retrieved. If you're using the default way of querying posts on a page you should be able to get away with query_posts, although it is not recomended. And, if you're using a custom loop, simply inject the new arguments into it:
<?php
$args = array();
switch ( $sort ):
case 'price':
$args['order'] = $order;
$args['orderby'] = 'meta_value_num';
$args['meta_key'] = 'price';
break;
default:
break;
endswitch;
$defaults = array( 'posts_per_page' => 33 );
$query = new WP_Query( wp_parse_args( $args, $defaults ) );
?>
You can add more variables, by creating more URLs and buttons to press, and more cases in the switch statement to extend the basic example above.
The first piece of code would go wherever you want your buttons to appear. The second piece of code goes before the third one, which goes before outputting the results.

How do i show wordpress attachments from current post?

So with my blog i have a photo attachment page but it only shows to photo's at a time, and those two photo's are used as the navigation and i hate that.
I want the attachment page to show all the photo's that goes along with the rest of that set.
Here is the current code
<div id="nav-images" class="navigation clearfix">
<div class="nav-next"><?php next_image_link() ?></div>
<div class="nav-previous"><?php previous_image_link() ?></div>
How do i change that to show all the post attachments?
To clarify, this doesn't work anymore - at least with version 3.5.2. I used this instead;
$attachments = get_children(
array(
'post_type' => 'attachment',
'post_parent' => get_the_ID()
)
);
foreach ($attachments as $attachment) {
// ...
}
Only resurrecting an old thread because this one ranks quite highly for this search term.
When you're on a page or post, you can get all of its attachments with the following:
global $post; // refers to the post or parent being displayed
$attachements = query_posts(
array(
'post_type' => 'attachment', // only get "attachment" type posts
'post_parent' => $post->ID, // only get attachments for current post/page
'posts_per_page' => -1 // get all attachments
)
);
foreach($attachements as $attachment){
// Do something exceedingly fancy
}
Since you're currently on an attachment page, you can get all the other attachments using the $post->post_parent value:
global $post; // refers to the attachement object
$attachements = query_posts(
array (
'post_type' => 'attachment', // only get "attachment" type posts
'post_parent' => $post->post_parent, // attachments on the same page or post
'posts_per_page' => -1 // get all attachments
)
);
To then display the attachment images, you can use the wp_get_attachment_image_src function. The attachment's ID will be available in each iteration of your foreach loop as $attachement->ID (if you use the same naming convention as my first example).
Since WordPress 3.6.0 you can also use get_attached_media.
$media = get_attached_media( 'image', $post->ID );
if(! empty($media)){
foreach($media as $media_id => $media_file){
$thumbnail = wp_get_attachment_image_src ( $media_id, 'thumbnail' );
$full = wp_get_attachment_url( $media_id );
echo '<img src="'.$thumbnail[0].'" alt="'.$media_file->post_title.'" />';
}
}

Resources