How to set taxonomy in custom plugin? - wordpress

I am trying to create a plugin, I need a custom post and taxonomy. But it can be accessible in admin side, but the taxonomy is not working on front-end.
This is how I registered the custom post and taxonomy:
function post_type_questionnaire()
{
$labels = array(
'name' => _x('Questionnaire', 'post type general name'),
'singular_name' => _x('Questionnaire', 'post type singular name'),
'add_new' => _x('Add New Question', 'questionnaire'),
'add_new_item' => __('Add New Questionnaire')
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'rewrite' => true,
'_builtin' => false, // It's a custom post type, not built in!
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => null,
'supports' => array('title',
//'editor',
/*'excerpt',
'thumbnail',
'trackbacks',
'custom-fields',
'comments',
'revisions',
'author',
'page-attributes'*/
));
register_post_type('questionnaire',$args);
}
add_action('init', 'post_type_questionnaire');
function create_questionnaire_taxanomies(){
register_taxonomy('qcategories','questionnaire', array(
'hierarchical'=>true,
'label'=>'Questionnaire Categories',
'rewrite' => array( 'slug' => 'questionnaire' )
));
}
add_action('init', 'create_questionnaire_taxanomies',0);
I am using a shortcode to display it in front-end.
by using the code below it shows all posts
$args = array(
'post_type' => 'questionnaire',
'posts_per_page' => -1,
);
$query = new WP_Query($args);
if ( $query->have_posts() ) { ?>
<?php while ( $query->have_posts() ) :query->the_post(); ?>
But when I try to specify a taxonomy term it doesn't work and this is the code:
$args = array(
'post_type' => 'questionnaire',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'qcategories',
'field' => 'slug',
'terms' => $atts["name"]
)
)
);
$query = new WP_Query($args);
if ( $query->have_posts() ) { ?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
When I tried to display the count of post in a template page it show nothing:
$term = get_term( 3, 'qcategories' );
echo $term->count;
This outputs nothing, so I believe that the taxonomy is not registering, can anybody help me to register the taxonomy in my custom plugin. Thanks in advance!
Edited
This is the output of $args:
array (size=3)
'post_type' => string 'questionnaire' (length=13)
'posts_per_page' => int -1
'tax_query' =>
array (size=1)
0 =>
array (size=3)
'taxonomy' => string 'qcategories' (length=11)
'field' => string 'slug' (length=4)
'terms' => string 'new' (length=3)

Looked like the code was just fine, as OP discovered there was just a little oversight in the code i.e in the plugin before registering taxonomy there was WordPress template tag if(is_admin()) which resulted the code work just fine in the Admin Panel, however when it was called in the front-end , there was no Taxonomy available for the WP_QUERY
Removing that admin_only if condition, code will just work fine.

Related

Use ACF Taxonomy Field as Variable in Wordpress Custom Post Type Loop

I'm attempting to create a custom Wordpress query, using an Advanced Custom Fields field as a variable in the loop.
The use case is a page has a custom loop on it. For example, a page about a venue displays a loop of events (the custom post type) at the bottom of the page. I want for the person creating the page to choose what event tag (a tag taxonomy on the CPT) they want to attach to the page. Then the loop runs with that field attaching to the tag query used as a variable.
Here's my code so far:
<?php if ( get_field('event_tag') ) : ?>
<?php
$event_tag = get_field('event_tag');
$args = array(
'post_type' => 'events',
'posts_per_page' => 3,
'tag_id' => $event_tag,
'meta_key' => 'event_start_date',
'orderby' => 'meta_value',
'order' => 'ASC',
'ignore_sticky_posts' => true
);
?>
<?php echo $event_tag; ?><!-- This is only here to check the variable -->
<?php else : ?>
<?php
$args = array(
'post_type' => 'events',
'posts_per_page' => 3,
'meta_key' => 'event_start_date',
'orderby' => 'meta_value',
'order' => 'ASC',
'ignore_sticky_posts' => true
);
?>
<?php endif; ?>
<?php $secondquery = new WP_Query( $args );
if ( $secondquery->have_posts() ) : while ( $secondquery->have_posts() ) : $secondquery->the_post(); ?>
I'm still wanting to sort by the event date, thus the meta_key and orderby. I'm not sure if that's affecting this. A couple things to note:
• That temporary line echoing the $event_tag does output the tag id (in this case 31).
• I've tried wrapping that tag_id in '', echoing it, etc. But it just displays nothing.
• Because this is querying a custom post type, I'm not sure if the standard tag even works. The tag is registered like this...if it matters.
// Taxonomy / Tags
function taxonomies_events_tags() {
$args = array(
'hierarchical' => false,
'label' => __( 'Event Tags','taxonomy general name'),
'singular_name' => __( 'Event Tag', 'taxonomy general name' ),
'rewrite' => true,
'query_var' => true,
'show_in_rest' => true
);
register_taxonomy( 'custom-tag', 'events', $args );
}
add_action( 'init', 'taxonomies_events_tags', 0 );
What do I need to change in my query to get the events in the specified tag to show, still ordered by event_start_date?
Thanks in advance.
You need to use a tax query to get events from a certain category. Assuming the $event_tag variable contains the tag id for the taxonomy term, the following piece of code should work:
$args = array(
'post_type' => 'events',
'posts_per_page' => 3,
'meta_key' => 'event_start_date',
'orderby' => 'meta_value',
'order' => 'ASC',
'ignore_sticky_posts' => true,
'tax_query' => array(
array(
'taxonomy' => 'custom-tag',
'field' => 'term_id',
'terms' => $event_tag
)
)
);

Wordpress Show custom post type specific category in post page?

I am new in development. I have created a custom post type manually, which is as in the code given below. I am unable to get post form specific category (Logo, Website) in Custom post type. Help me to solve this.
function my_custom_taxonomies(){
$lables = array(
'name' => 'Type',
'singular_name' => 'my_custom_taxonomiesType',
'all_items' => 'All Types',
'add_new_item' => 'Add Type',
'edit_item' => 'Edit Type',
'search_item' => 'Search Type',
'parent_item' => 'Parent Type',
'parent_item_colon' => 'Parent Type',
'update_item' => 'Update Type',
'new_item_name' => 'New Type Name',
'menu_name' => 'Type'
);
$args = array(
'labels' => $lables,
'query_var' => ture,
'rewrite' => array('slug' => 'type'),
'hierarchical' => true,
'show_ui' => true,
'show_admin_column' => true,
);
register_taxonomy('type', array('portfolio'), $args);
}
add_action('init','my_custom_taxonomies');
I am trying this code, but cannot get it to work.
$args = array( 'post_type' => 'portfolio', 'category_name' => 'logo', 'posts_per_page' => 10 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<ul>
<li><?php the_title(); ?></li>
</ul>
<?php echo '<div class="entry-content">';
//the_content();
echo '</div>';
endwhile;?>
Just Use this as you have registered taxonomy. You can refere about WP_Query here
$query = new WP_Query( array(
'post_type' => 'portfolio',
'tax_query' => array(
array (
'taxonomy' => 'type',
'field' => 'slug',
'terms' => 'logo',
)
),
) );

wordpress shortcode how to filter according to a custom taxonomy?

I have created a custom post type (school) and a custom taxonomy (region) attached to it.
Everything works great except I want to create a shortcode that only get the school that belongs to a specific entry in that custom taxonomy.
That means when you will write the shortcode you will pass a region name, and only schools that belong to that region will return from the database.
I managed to use the shortcode, but not to filter according to the region.
This is my custon taxonomy:
$taxonomies['regions'] = array(
'hierarchical' => true,
'query_var' => 'school_region',
'rewrite' => array(
'slug' => 'schools/region'
),
'labels' => array(
'name' => __('Region'),
'singular_name' => __('Region'),
'add_new' => __('Add New Region'),
'add_new_item' => __('Add New Region'),
'edit_item' => __('Edit Region'),
'new_item' => __('Add New Region'),
'view_item' => __('View Region'),
'search_items' => __('Search Regions'),
'not_found' => __('No Region Found'),
'not_found_in_trash' => __('No Regions Found In Trash'),
),
);
And this is my shortcode:
add_shortcode('rs_school',function($atts, $content=null){
$loop = new WP_Query( array(
'post_type' => 'rs-school',
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'DESC',
) );
//var_dump($loop);
if($loop->have_posts() ){ ?>
<ul class="related">
<?php
while ($loop->have_posts()) {
$loop->the_post();
//$meta = get_post_meta(get_the_ID(), '');
$terms = get_the_terms( $post->ID , 'regions' );
var_dump($terms);
if (in_array($theregion, $terms)){
?>
<li>
<?php echo get_the_title() ?>
</li>
<?php
}
} ?>
</ul>
<div class="clearfix"></div>
<?php
}
});
How can I do that?
best regards
so managed to work it out. so hopefully will help others:
i send the term id to the short code, and use it to fillter it:
$atts = shortcode_atts(
array(
'region' => 15,
), $atts, 'rs_school' );
and then filter it like so:
$loop = new WP_Query( array(
'post_type' => 'rs-school',
'posts_per_page' => -1,
'orderby' => 'date', // Purely optional - just for some ordering
'order' => 'DESC', // Ditto
'tax_query' => array(
array(
'taxonomy' => 'regions', //or tag or custom taxonomy
'field' => 'id',
'terms' => $atts['region']
)
)
) );
hope it will help others.

Ordering custom post types

I'm registering a new custom post type like this:
function news_register() {
$labels = array(
'name' => _x('News', 'post type general name'),
'singular_name' => _x('News Item', 'post type singular name'),
'add_new' => _x('Add New News Article', 'resources item'),
'add_new_item' => __('Add New News Article'),
'edit_item' => __('Edit News Article'),
'new_item' => __('New News Article'),
'view_item' => __('View News Article'),
'search_items' => __('Search News Articles'),
'not_found' => __('Nothing found'),
'not_found_in_trash' => __('Nothing found in Trash'),
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'rewrite' => true,
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => 8,
'supports' => array('title','editor', 'excerpt', 'thumbnail', 'excerpt')
);
register_post_type( 'news' , $args );
}
add_action('init', 'news_register');
And I'm then trying to query those post types and order them by title using:
$news = new WP_Query(array(
'post_type' => 'news',
'orderby' => 'name',
'order' => 'DESC'
));
Or:
$args = array( 'post_type' => 'news', 'posts_per_page'=>5, 'orderby'=>'title','order'=>'ASC');
$news = new WP_Query( $args );
Neither of which order by the post title at all. The news posts are test articles that are called 'aaa', 'bbb' and 'ccc.
How can I change my query to get the posts by title order?
EDIT:
I have this code in functions, but removing it doesn't seem to change anything.
add_filter( 'pre_get_posts','change_my_post_order' );
function change_my_post_order( $query ) {
global $wp_query;
if ( is_category() ) {
$query->set( 'orderby', 'title' );
$query->set( 'order', 'asc' );
}
return $query;
}
Adding "'suppress_filters' => true," to the query doesn't seem to make any difference either.
Your pre_get_posts action is wrong. You should make sure that you only target the front end and only the main query. Your action should look like this
add_action( 'pre_get_posts','change_my_post_order' );
function change_my_post_order( $query ) {
if ( !is_admin() && $query->is_main_query() && $query->is_category() ) {
$query->set( 'orderby', 'title' );
$query->set( 'order', 'asc' );
}
}

Wordpress - Custom Taxonomy Pagination

I'm using:
Wordpress 3.4
WP-PageNavi 2.82
I register custom taxonomy (catalog)
<?php
add_action('init', 'pca_register_taxonomy', 0);
function pca_register_taxonomy()
{
register_taxonomy('catalog', null,
array(
'label' => __('Catalogs', __),
'labels' => array(
'name' => __('Catalogs', __),
'singular_name' => __('Catalog', __),
'search_items' => __('Search Catalogs', __),
'popular_items' => __('Popular Catalogs', __),
'all_items' => __('All Catalogs', __),
'parent_item' => __('Parent Catalog', __),
'parent_item_colon' => __('Parent Catalog', __),
'edit_item' => __('Edit Catalog', __),
'update_item' => __('Update Catalog', __),
'add_new_item' => __('Add New Catalog', __),
'new_item_name' => __('New Catalog Name', __),
'separate_items_with_commas' => __('Separate catalogs with commas', __),
'add_or_remove_items' => __('Add or remove catalogs', __),
'choose_from_most_used' => __('Choose from the most used catalogs', __),
'menu_name' => __('Catalogs', __)
),
'public' => true,
'show_in_nav_menus' => true,
'show_ui' => true,
'show_tagcloud' => false,
'hierarchical' => true,
'query_var' => true,
'rewrite' => array(
'slug' => 'catalog',
'with_front' => true,
'hierarchical' => true
),
'capabilities' => array(
'manage_terms',
'edit_terms',
'delete_terms',
'assign_terms'
)
)
);
}
?>
I register custom post type (product)
<?php
add_action('init', 'pca_register_post_type');
function pca_register_post_type()
{
register_post_type('product',
array(
'label' => __('Products', __),
'labels' => array(
'name' => __('Products', __),
'singular_name' => __('Product', __),
'add_new' => __('Add New', __),
'add_new_item' => __('Add New Product', __),
'edit_item' => __('Edit Product', __),
'new_item' => __('New Product', __),
'all_items' => __('All Products', __),
'view_item' => __('View Product', __),
'search_items' => __('Search Products', __),
'not_found' => __('No products found', __),
'not_found_in_trash' => __('No products found in Trash', __),
'parent_item_colon' => '',
'menu_name' => __('Products', __)
),
'description' => '',
'public' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_nav_menus' => true,
'show_in_menu' => true,
'show_in_admin_bar' => true,
'menu_position' => 20,
'capability_type' => 'post',
'meta_cap' => true,
'hierarchical' => false,
'supports' => array(
'title',
'editor',
'thumbnail',
'page-attributes',
'post-formats'
),
'taxonomies' => array('catalog'),
'has_archive' => false,
'rewrite' => array(
'slug' => 'products',
'with_front' => true,
'feeds' => false,
'pages' => true
),
'query_var' => true,
'can_export' => true
)
);
}
?>
Then I create a new file for tax -> taxonomy-catalog.php
In this file, I query all products (custom post type) from specified catalog (tax):
<?php
$paged = get_query_var('paged');
$paged = ($paged) ? $paged : 1;
$products = new WP_Query(array(
'catalog' => $catalog_data->slug, // $catalog_data is the current taxonomy (woman)
'post_type' => 'product',
'posts_per_page' => 12,
'paged' => $paged
));
?>
<?php while ($products->have_posts()) : $products->the_post(); ?>
// Show title, content ... everything ok
<?php endwhile; ?>
<?php if (function_exists('wp_pagenavi')) wp_pagenavi(array('query' => $products)); ?>
<?php wp_reset_postdata(); ?>
Pagination is displayed correctly but when I click on page 2 or over I have a 404 error.
Works -> mywebsite.com/catalog/woman
Works not -> mywebsite.com/catalog/woman/page/2
I already refreshed permalinks.
Any idea to fix this ? thanks
Put this into your "functions.php" and then regenerate permalinks.
It works to me!
function taxonomy_rewrite_fix($wp_rewrite) {
$r = array();
foreach($wp_rewrite->rules as $k=>$v){
$r[$k] = str_replace('catalog=$matches[1]&paged=','catalog=$matches[1]&page=',$v);
}
$wp_rewrite->rules = $r;
}
add_filter('generate_rewrite_rules', 'taxonomy_rewrite_fix');
The key is to replace "paged" to "page" into the rewrite rule for your custom taxonomy.
This is my first contribution here. Hope I help you.
Once I have faced problem about this and passed hard times hrs to hrs by pulling hair. I googled and didn't found any specific solution about the topics. I found several talents' article but they weren't satisfying my problems. Actually custom taxonomy archive page pagination is depends on some settings of arguments of related functions. So I am actually going here sharing my thoughts of solving the taxonomy archive pagination problem.
Five things you need for custom taxonomy archive page pagination working perfectly :
( 1 ) Don't put exclude_from_search parameter key as register_post_type argument parameter or
if mention set it 'exclude_from_search' => false. By default it is set false if not mentioned.
( 2 ) The taxonomy that will be use with the custom post type set
'taxonomies' => 'custom_taxonomy_name' as register_post_type argument parameter or
use register_taxonomy_for_object_type() directly.
Custom taxonomies still need to be registered with register_taxonomy().
( 3 ) While querying within new WP_Query ($args)
i ) If not set in admin `static front page` use before `new WP_Query($args)`
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
and use $query = new WP_Query( array( 'paged' => $paged ) );
ii ) If set in admin static front page use before 'new WP_Query($args)'
$paged = ( get_query_var('page') ) ? get_query_var('page') : 1;
and use $query = new WP_Query( array( 'page' => $paged ) );
Remember to use posts_per_page and paged parameter in new WP_Query($arg) argument array.
If not set static front page then you should use page parameter in new WP_Query ($arg) argument array
( 4 ) Use Wordpress paginate_links( $args ) function like the example below to render pagination in archive template file.
<?php $big = 999999999; // need an unlikely integer
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%', or '/paged=%#%', // if using pretty permalink
'current' => max( 1, get_query_var('paged') ),
'total' => $query->max_num_pages ) ); // Here $max_num_pages is the properties of new WP_Query() object . It is total number of pages. Is the result of $found_posts / $posts_per_page
?>
( 5 ) The paginate_links() function output the ul li listing with page-numbers class.
If you use bootstrap inject pagination class to the ul with the help of javascript or jquery and a nice fancy pagination will be output.
Hope you can now enjoy pagination in the taxonomy archive template without any 404 problem :-)
What helped me is to set "Blog pages show at most" in Reading Settings to 1. Then it works.
With the default 10, it throws 404 error on page 2. On page 1 it's all perfect.
So given this works, the solution is to set "Blog pages show at most" to 1 only for those taxonomies or categories you need. The code you should place inside functions.php is here: https://forums.envato.com/t/wordpress-custom-page-type-taxonomy-pagination/76549/12
Basically that's
get_query_var('page')
that holds the page number
from the working code:
global $query_string;
$page_index = max(1, get_query_var('page'));
parse_str($query_string, $queryParams);
$queryParams['paged'] = $page_index;
$queryParams['posts_per_page'] = $posts_per_page;
query_posts($queryParams);
Use query_posts instead of wp_query. It should work.
This is my Code.
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'paged' => $paged,
'orderby' => 'asc',
'tax_query' => array(
array(
'taxonomy' => "$term->taxonomy",
'terms' => "$term->name",
'field' => 'slug'
)
)
);
$query = new WP_Query( $args );
if($query->have_posts() ) :
// your code
?>
<?php endwhile; endif;
wp_pagenavi();?>
When you create any CPT then you need to add this function.flush_rewrite_rules();It will manage/adjust/reassign your memory.So please add this line your code will work.Precaution.1: Add this function : flush_rewrite_rules();2:Your pagination function (wp_pagenavi()) will call just below the endwhile;I 'm sure,your pagination will work and let me know if it will not work.
Thanking you.

Resources