I've been banging my head against the wall trying to save a custom meta box select option. I am having a hard time figuring out what I actually target to save the value, since I have multiple options in the dropdown. I try to target the select name="XXX" but still no luck. Any help would be greatly appreciated.
Here is my code to show the select option dropdown:
<?php
$accessory_product_args = [
'posts_per_page' => -1,
'tax_query' => [
'relation' => 'AND',
[
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'accessories'
],
],
'post_type' => 'product',
'orderby' => 'title',
];
$accessory_product = new WP_Query( $accessory_product_args ); ?>
<select name="_accessories_product_one" id="_accessories_product_one" class="widefat">
<?php while ( $accessory_product->have_posts() ) : $accessory_product->the_post();
$title_one = get_the_title();
$postid_one = get_the_ID(); ?>
<option value="<?=$postid_one?>" <?php selected( '_accessories_product_one[select_field_0]', $postid_one); ?>>
<?=$title_one?>
</option>
<?php endwhile; ?>
</select>
<?php
//this below is used for testing to see if i have saved the value or not:
$dropdown_option = get_option( '_accessories_product_one' ); // Array
$dropdown_value = $dropdown_option ['select_field_0']; // Option value
var_dump($dropdown_option);
var_dump($dropdown_value);
?>
This code is the saving:
<?php
if (isset($_POST['_accessories_product_one']) {
update_post_meta( $post_id, '_accessories_product_one', $_POST['_accessories_product_one']);
} ?>
Any help would be greatly appreciated.
EDIT:
I am using this within the woocommerce product screen - not Page edit or Post edit or a plugin edit screen.
Here is a more verbose paste of the full code I am using:
function custom_product_basic_load() {
add_action( 'add_meta_boxes_product' , 'custom_product_basic_add_meta_boxes_product' );
add_meta_box( 'custom_product_basic_metabox' , __( 'Product Layout' ) , 'custom_product_basic_metabox' , 'product' , 'normal' , 'high' );
add_action( 'save_post' , 'custom_product_basic_save_post' , 10 , 3 );
}
add_action( 'load-post.php' , 'custom_product_basic_load' );
add_action( 'load-post-new.php' , 'custom_product_basic_load' );
function custom_product_basic_metabox( $post ) {?>
<input type="hidden" name="product_type" value="simple" />
<?php
$accessory_product_args = [
'posts_per_page' => -1,
'tax_query' => [
'relation' => 'AND',
[
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'accessories'
],
],
'post_type' => 'product',
'orderby' => 'title',
];
$accessory_product = new WP_Query( $accessory_product_args ); ?>
<select name="_accessories_product_one" id="_accessories_product_one" class="widefat">
<?php while ( $accessory_product->have_posts() ) : $accessory_product->the_post();
$title_one = get_the_title();
$postid_one = get_the_ID(); ?>
<option value="<?=$postid_one?>" <?php selected( '_accessories_product_one[select_field_0]', $postid_one); ?>>
<?=$title_one?>
</option>
<?php endwhile; ?>
</select>
<?php
$dropdown_option = get_option( '_accessories_product_one' ); // Array
$dropdown_value = $dropdown_option ['select_field_0']; // Option value
var_dump($dropdown_option);
var_dump($dropdown_value);
?>
<?php }
function custom_product_basic_save_post( $post_id ) {
if (isset($_POST['_accessories_product_one'])) {
update_post_meta( $post_id, '_accessories_product_one', $_POST['_accessories_product_one']);
}
}
Try this. you are storing the value in post_meta. but getting from get_option. Do not use get_option to get the post meta value.
function custom_product_basic_load() {
add_action( 'add_meta_boxes_product' , 'custom_product_basic_add_meta_boxes_product' );
add_meta_box( 'custom_product_basic_metabox' , __( 'Product Layout' ) , 'custom_product_basic_metabox' , 'product' , 'normal' , 'high' );
add_action( 'save_post' , 'custom_product_basic_save_post' , 10 , 3 );
}
add_action( 'load-post.php' , 'custom_product_basic_load' );
add_action( 'load-post-new.php' , 'custom_product_basic_load' );
function custom_product_basic_metabox( $post ) {?>
<input type="hidden" name="product_type" value="simple" />
<?php
echo $productLayout = get_post_meta( $post->ID, '_accessories_product_one',true);
$accessory_product_args = [
'posts_per_page' => -1,
'tax_query' => [
'relation' => 'AND',
[
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'accessories'
],
],
'post_type' => 'product',
'orderby' => 'title',
];
$accessory_product = new WP_Query( $accessory_product_args ); ?>
<select name="_accessories_product_one" id="_accessories_product_one" class="widefat">
<?php while ( $accessory_product->have_posts() ) : $accessory_product->the_post();
$title_one = get_the_title();
$postid_one = get_the_ID(); ?>
<option value="<?=$postid_one?>" <?php selected( $productLayout, $postid_one); ?>>
<?=$title_one?>
</option>
<?php endwhile; ?>
</select>
<?php
}
function custom_product_basic_save_post( $post_id ) {
if (isset($_POST['_accessories_product_one'])) {
update_post_meta( $post_id, '_accessories_product_one', $_POST['_accessories_product_one']);
}
}
Related
I'm working on a WP_Query loop that is suppose to show the list of posts in a following way
+ Custom taxonomy term 1
++ Post 1
++ Post 2
+ Custom taxonomy term 2
++ Post 1
++ Post 2
So in general it will work for CPT called 'career'. In a real life my custom taxonomy (job-category) is like: Drivers, Logistics, HR etc. And to each of such taxonomy/category I've got created specific posts. There is also a custom taxonomy called job-country which suggests the territory.
To achieve the way of showing my posts I am using the following code:
<?php
$terms = get_terms([
'taxonomy' => 'job-category',
'hide_empty' => true,
'orderby' => 'count',
'order' => 'DESC'
]);
usort( $terms, function( $a, $b ) {
$a_ste = (int) get_term_meta( $a->term_id, 'stick_to_end', true );
$b_ste = (int) get_term_meta( $b->term_id, 'stick_to_end', true );
if ($a_ste == $b_ste) return 0;
return ($a_ste < $b_ste) ? -1 : 1;
} );
if ($terms) { //categories exists
foreach ($terms as $category) { ?>
<h2 class="category-title">
<?= $category->name ?>
</h2>
<?php
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'career',
'tax_query' => [
[
'taxonomy' => 'job-category',
'field' => 'term_id',
'terms' => $category->term_id,
]
]
));
if ( $posts ) {
foreach( $posts as $post ) {
setup_postdata( $post );
include 'JobListThumb.php';
};
wp_reset_postdata();
}
}
} else { //no categories
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type' => 'career'
));
if ( $posts ) {
foreach( $posts as $post ) {
setup_postdata( $post );
include 'JobListThumb.php';
};
wp_reset_postdata();
}
}
?>
And it works. But because of certain reasons (working on an ajax filtering function) I need to achieve the same thing using traditional wp_query.
This is what I've got:
$args = array(
'orderby' => 'date', // we will sort posts by date
'order' => $_POST['date'], // ASC or DESC
'post_type' => 'career',
);
// for taxonomies / categories
if( isset( $_POST['categoryfilter'] ) && isset( $_POST['taxonomyfilter'] ))
$args['tax_query'] = array(
'relation' => 'AND',
array(
'taxonomy' => 'job-category',
'field' => 'id',
'terms' => $_POST['categoryfilter']
),
array(
'taxonomy' => 'job-country',
'field' => 'id',
'terms' => $_POST['taxonomyfilter']
)
);
// if you want to use multiple checkboxes, just duplicate the above 5 lines for each checkbox
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
echo '<h2>' . $query->post->post_title . '</h2>';
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
die();
But I've stucked in a place - how to add those terms / elements to the query? Obviously cannot mix get_terms with wpquery by simply copying instead echo'ing the title.
Do you have any suggestions how to solve this?
I trying to get products by post author id using a WC_Query in WooCommerce, so I tried to include a new custom meta_key "_author", with the following:
add_filter( 'woocommerce_product_data_store_cpt_get_products_query', 'handling_custom_meta_query_keys', 10, 3 );
function handling_custom_meta_query_keys( $wp_query_args, $query_vars ) {
$meta_key = '_author';
if ( ! empty( $query_vars[$meta_key] ) ) {
$wp_query_args['meta_query'][] = array(
'key' => $meta_key,
'value' => esc_attr( $query_vars[$meta_key] ),
'operator' => '==',
);
}
return $wp_query_args;
}
Then I tried to use it with wc_get_products():
$product_list = wc_get_products( array('_author' => get_current_user_id()) );
but it return null array. Any idea?
You can simply get products by author Id in a WC_Query using the undocumented parameter "author'" as follow:
$products = wc_get_products( array(
'status' => 'publish',
'limit' => -1,
'author' => get_current_user_id()
) );
You will get an array of WC_Product Objects
You can use custom query like this
<?php
$authorID = get_the_author_meta('ID');
$args = array(
'post_type' => 'product',
'post_status' => 'publish'
'posts_per_page' => 12,
'product_cat' => 'pants'
'author' => $authorID
);
$loop = new WP_Query( $args );
?>
<div class="author_products">
<?php if ( $loop->have_posts() ) { ?>
<ul class="author_pubproducts">
<?php while ( $loop->have_posts() ) : $loop->the_post();
woocommerce_get_template_part( 'content', 'product' );
endwhile; ?>
</ul>
<?php
} else {
echo __( 'No products found', 'textdomain' );
}
wp_reset_postdata();
?>
Hope it's work
I followed the tutorial from here. But I want to make it to filter multi categories/taxonomies with ajax load more.
After I set the filter, when I click load more it will show all category posts, not the category that is checked
Is there anyway to show the categories checked when load more.
Filter checkboxes
Index.PHP
<form id="misha_filters" action="#">
<div class="checkbox-wrap">
<input type="checkbox" id="fi1-all" name="categoryfilter-all" value="all" checked>
<label for="fi1-all" class="cat-all">
<?php
$args = array(
'posts_per_page' => -1,
'post_status' => 'publish',
'category' => '-1', // except uncategorized
);
$posts_array = get_posts( $args );
$total_post = count($posts_array);
?>
All (<?php echo $total_post ?>)
<span class="icon-check"><?php include 'inc/vectors/check-for-checkbox-white.svg' ?></span>
</label>
</div>
<?php
if( $terms = get_terms( 'category', 'orderby=name' ) ) :
$a = 0;
foreach ( $terms as $term ) :
$a++;
if ( $term->slug !== 'uncategorized' ) :
?>
<div class="checkbox-wrap">
<input type="checkbox" id="fi1-<?php echo $a ?>" name="categoryfilter-<?php echo $a ?>" value="<?php echo $term->term_id ?>">
<label for="fi1-<?php echo $a ?>" class="cat-<?php echo $term->slug ?>">
<?php echo $term->name ?> (<?php echo $term->count; ?>)
<span class="icon-check"><?php include 'inc/vectors/check-for-checkbox-white.svg' ?></span>
</label>
</div>
<?php
endif;
endforeach;
endif;
?>
function.php
add_action( 'wp_enqueue_scripts', 'misha_script_and_styles');
function misha_script_and_styles() {
global $wp_query;
wp_register_script( 'misha_scripts', get_stylesheet_directory_uri() . '/inc/script-filter-loadmore.js', array('jquery') );
wp_localize_script( 'misha_scripts', 'misha_loadmore_params', array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php',
'posts' => json_encode( $wp_query->query_vars ),
'current_page' => $wp_query->query_vars['paged'] ? $wp_query->query_vars['paged'] : 1,
'max_page' => $wp_query->max_num_pages
) );
wp_enqueue_script( 'misha_scripts' );
}
add_action('wp_ajax_loadmorebutton', 'misha_loadmore_ajax_handler');
add_action('wp_ajax_nopriv_loadmorebutton', 'misha_loadmore_ajax_handler');
function misha_loadmore_ajax_handler(){
$taxonomy = 'category';
$taxonomy_terms = get_terms( $taxonomy, array(
'hide_empty' => 0,
'fields' => 'ids',
'exclude' => get_cat_ID('uncategorized'),
));
$form_filter_checkboxes = array($_POST['categoryfilter-1'], $_POST['categoryfilter-2'],
$_POST['categoryfilter-3'], $_POST['categoryfilter-4'],
$_POST['categoryfilter-5'], $_POST['categoryfilter-6'],
$_POST['categoryfilter-7']);
$params = json_decode( stripslashes( $_POST['query'] ), true );
$params['paged'] = $_POST['page'] + 1;
$params['post_status'] = 'publish';
$params['posts_per_page'] = '3';
$params['tax_query'] = array(
'taxonomy' => $taxonomy,
'field' => 'id',
'terms' => $form_filter_checkboxes,
)
;
query_posts( $params );
global $wp_query;
if( have_posts() ) :
while( have_posts() ): the_post();
get_template_part( 'template-parts/post/post-type-content', get_post_format() );
endwhile;
endif;
die;
}
add_action('wp_ajax_mishafilter', 'misha_filter_function');
add_action('wp_ajax_nopriv_mishafilter', 'misha_filter_function');
function misha_filter_function(){
$params = array(
'orderby' => 'date',
'order' => 'DESC',
'post_status' => 'publish',
'posts_per_page' => 2
);
$taxonomy = 'category';
$taxonomy_terms = get_terms( $taxonomy, array(
'hide_empty' => 0,
'fields' => 'ids',
'exclude' => get_cat_ID('uncategorized'),
));
$form_filter_checkboxes = array($_POST['categoryfilter-1'], $_POST['categoryfilter-2'],
$_POST['categoryfilter-3'], $_POST['categoryfilter-4'],
$_POST['categoryfilter-5'], $_POST['categoryfilter-6'],
$_POST['categoryfilter-7']);
if ( $_POST['categoryfilter-all'] === 'all') :
$params['tax_query'] = array(
array(
'taxonomy' => $taxonomy,
'field' => 'id',
'terms' => $taxonomy_terms,
)
);
else :
$params['tax_query'] = array(
array(
'taxonomy' => $taxonomy,
'field' => 'id',
'terms' => $form_filter_checkboxes,
)
);
endif;
query_posts( $params );
global $wp_query;
if( have_posts() ) :
ob_start();
while( have_posts() ): the_post();
echo $_POST['categoryfilter-all'];
get_template_part( 'template-parts/post/post-type-content', get_post_format() );
endwhile;
$posts_html = ob_get_contents();
ob_end_clean();
else:
$posts_html = '<p>Nothing found for your criteria.</p>';
endif;
echo json_encode( array(
'posts' => serialize( $wp_query->query_vars ),
'max_page' => $wp_query->max_num_pages,
'found_posts' => $wp_query->found_posts,
'content' => $posts_html
) );
die();
}
JS File
jQuery(function($){
/*
* Load More
*/
$('#misha_loadmore').click(function(){
$.ajax({
url : misha_loadmore_params.ajaxurl, // AJAX handler
data : {
'action': 'loadmorebutton', // the parameter for admin-ajax.php
'query': misha_loadmore_params.posts, // loop parameters passed by wp_localize_script()
'page' : misha_loadmore_params.current_page // current page
},
type : 'POST',
beforeSend : function ( xhr ) {
$('#misha_loadmore').text('Loading...'); // some type of preloader
},
success : function( posts ){
if( posts ) {
$('#misha_loadmore').text( 'More posts' );
$('#misha_posts_wrap').append( posts ); // insert new posts
misha_loadmore_params.current_page++;
if ( misha_loadmore_params.current_page == misha_loadmore_params.max_page )
$('#misha_loadmore').hide(); // if last page, HIDE the button
} else {
$('#misha_loadmore').hide(); // if no data, HIDE the button as well
}
}
});
return false;
});
/*
* Filter
*/
$('#misha_filters').submit(function(){
$.ajax({
url : misha_loadmore_params.ajaxurl,
data : $('#misha_filters').serialize(), // form data
dataType : 'json', // this data type allows us to receive objects from the server
type : 'POST',
beforeSend : function(xhr){
$('#misha_filters').find('button').text('Filtering...');
},
success : function( data ){
// when filter applied:
// set the current page to 1
misha_loadmore_params.current_page = 1;
// set the new query parameters
misha_loadmore_params.posts = data.posts;
// set the new max page parameter
misha_loadmore_params.max_page = data.max_page;
// change the button label back
$('#misha_filters').find('button').text('Apply filter');
// insert the posts to the container
$('#misha_posts_wrap').html(data.content);
// hide load more button, if there are not enough posts for the second page
if ( data.max_page < 2 ) {
$('#misha_loadmore').hide();
} else {
$('#misha_loadmore').show();
}
}
});
// do not submit the form
return false;
});
});
$params = json_decode( stripslashes( $_POST['query'] ), true );
The above line is not calling the filter query loop. That is why, you are not able to get the queried loop, set by misha_filter_function(){}.
Update (Fixed): Please check the update below.
The actual problem was
$_POST['query']
is returning not a JSON format data instead it's returning serialized form of data.
So that using json_encode doesn't make any sense. Simply change this line
$params = json_decode( stripslashes( $_POST['query'] ), true );
to this
$params = unserialize( stripslashes( $_POST['query']) );
Then it must work. All the best (y)
I don't know if you still have a problem, but here's my solution by simply change:
echo json_encode( array(
'posts' => serialize( $wp_query->query_vars ),
'max_page' => $wp_query->max_num_pages,
'found_posts' => $wp_query->found_posts,
'content' => $posts_html
) );
TO
echo json_encode( array(
'posts' => json_encode( $wp_query->query_vars ),
'max_page' => $wp_query->max_num_pages,
'found_posts' => $wp_query->found_posts,
'content' => $posts_html
) );
I just changed serialize to json_encode and this is the right way and you will get your terms posts!
You should not use unserialize the way Deepak did. It's very insecure. There's a red warning in the manual, and you can easily find explanations on why it's dangerous by searching for PHP object injection.
Do yourself a favor and use json_encode/decode. It shouldn't make a difference since query_vars is a simple array.
I'm developing a Latin Literature digital library for my thesis.
Right now I'm working on the author's archive page.
Authors is a Custom Post Type registered as 'auctores' with a custom taxonomy assigned to it named 'periodi'.
In the archive page (archive-auctores.php) I'd like to show all the authors listed by a meta field and other three columns: Periods (which refers to the custom taxonomy that I'd like to make a filter), Number of books (there should be the number of books (cpt) assigned to that author) and Gener (where to display all the literary genres of the books assigned to that author and it would be another taxonomy assigned to the book cpt via the cpt-onomies plugin). The number column should be sortable (asc/desc) while i'd like to make a filter for periods and for kinds.
I.E. --> opening the archive page it will show up the complete list of authors. So it should be possible to filter the authors for period and the page should show just the authors "tagged" with that specific taxonomy term.
I thought I had found a solution here, but when I try to select one term in the drop down the list remain the same.
I'm surely missing something.
That's the code of my template right now:
<form method="post" action="<?php the_permalink()?>">
<select name="periodi" id="selectperiodo" class="postform" onchange="submit();">
<option value="">Tutti i periodi</option>
<?php
$args = array(
'orderby' => 'ID',
'order' => 'ASC',
'hide_empty' => false,
'fields' => 'all',
'hierarchical' => true,
'pad_counts' => false,
'get' => '',
'child_of' => 0,
'parent' => '',
'childless' => false,
'cache_domain' => 'core',
'update_term_meta_cache' => true,
'meta_query' => '',
'parent' => 0
);
$terms = get_terms('periodi', $args);
if ( $terms ) {
foreach ( $terms as $term ) {?>
<option <?php if($term->slug == $_POST['periodi']){ echo 'selected="selected"';} ?> value="<?php echo esc_attr( $term->slug )?>"><?php echo esc_html( $term->name ) ?></option>
<?php }
}
?>
</select>
</form>
<table class="dataTable table table-hover">
<tr>
<th>Nome</th>
<th>Periodo</th>
<th>Opere</th>
<th>Genere</th>
</tr>
<?php $auctores_query = new WP_Query(array(
'post_type' => 'auctores',
'posts_per_page' => -1,
'order' => 'ASC',
'meta_key' => 'nome_classico',
'orderby' => 'meta_value',
)
); ?>
<?php $j = 0 ?>
<?php while ($auctores_query->have_posts()) : $auctores_query->the_post(); ?>
<?php $additional_class = (++$j % 2 == 0) ? 'even' : 'odd'; ?>
<tr class="<?php echo $additional_class ?>">
<td><?php the_title( '<h3 class="entry-title">', '</h3>' )?></td>
<td>
<?php
$terms = get_the_terms( $post->ID, 'periodi' );
if ( $terms && ! is_wp_error( $terms ) ) :
$periodi_links = array();
foreach ( $terms as $term ) {
$periodi_links[] = $term->name;
}
$on_draught = join( ", ", $periodi_links );
?>
<?php echo $on_draught; ?>
<?php endif; ?>
</td>
<td><span class="badge"><?php
$args = array('post_type' => 'texti',
'tax_query' => array (
array ( 'taxonomy' => 'auctores',
'field' => 'id',
'terms' => get_the_ID()
)
));
$query = new WP_Query( $args );
// the query
echo $query->found_posts;
?></span></td>
</tr>
<?php endwhile; ?>
</table>
Any help would be really appreciated.
Thanks!
IF you want the list of authors to be limited based on the drop-down selection, then you'll need to modify the query and utilize the Taxonomy Query Parameters:
Modify the code so that it responds to the form post as follows:
// First we have to take the args out into a variable
$args = array(
'post_type' => 'auctores',
'posts_per_page' => -1,
'order' => 'ASC',
'meta_key' => 'nome_classico',
'orderby' => 'meta_value'
);
// Then, we watch for the post and modify the args if appropriate:
if ( ! empty( $_POST['periodi'] ) ) {
$args['tax_query'] = array(
array(
'taxonomy' => 'periodi',
'field' => 'slug',
'terms' => $_POST['periodi']
)
);
}
// Then we can execute the query:
$auctores_query = new WP_Query( $args );
I currently have the option in my CMS, to add tags to my custom post type single page.
Now, I am wanting to display this tag as a 'featured' item.
So, In my taxonomy-'filename', I use the following code which gathers the tags and displays them in the taxonomy page:
<?php
$args = array(
'tag_slug__and' => array('sector1'),
'post_type' => array( 'sectors' )
);
$loop = new WP_Query( $args );
while ($loop->have_posts() ) : $loop->the_post();
?>
<a href="<?php echo get_permalink(); ?>">
<?php echo "<div class='col-md-6' style='margin-bottom:20px;'>"; ?>
<div class="row mobilemargin">
<div class="categorytiletextsector1">
<div class="col-md-6 col-sm-6 col-xs-12 nopr"><?php echo get_the_post_thumbnail( $page->ID, 'categoryimage', array('class' => 'sector1img hovereffect')); ?> </div>
<div class="col-md-6 col-sm-6 col-xs-12">
<div class="testdiv">
<h5><?php the_title(); ?></h5>
<p><?php the_excerpt(); ?></p>
</div>
</div>
</div>
</div>
<?php echo "</div>"; ?>
</a>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
Now, my issue is, this will display the selected tag on every category page now, as it is set on the taxonomy page.
How can I make this only set on the current category.
So If my item is in the 'category A', only the category page of 'A' would show this, using the items category?
Any help would be great
Edit.
Used this code, hoping this should work, but no luck
$args = array(
'tag_slug__and' => array( 'sector1' ),
'post_type' => array( 'sectors' ),
'tax_query' => array(
array(
'taxonomy' => 'sectors',
'terms' => get_queried_object_id(),
),
),
);
Your problem is your custom query. One very important note here is, never ever change replace the main query with a custom one on any type of archive page or the home page. I have explained everything in detail in this post recently. Make sure to read it and all the linked posts as this will benefit you a lot
Your solution would be to remove your custom query and replace this with the default loop that we all know
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
// Your template tags and html mark up
}
}
If you need to change anything in the main query, use pre_get_posts to do so
EDIT
Your best idea here would be to use a full tax_query to display posts that is in the selected taxonomy term and tag
You can try something like this: (Requires at least PHP 5.4+. Also, this untested)
$q = get_queried_object();
$args = [
'post_type' => 'sectors',
'tax_query' => [
[
'taxonomy' => $q->taxonomy,
'terms' => $q->term_id,
'include_children' => false // Exclude child terms
],
[
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => 'sector1', //I believe this is the slug
],
],
];
For older PHP versions, use the following
$q = get_queried_object();
$args = array(
'post_type' => 'sectors',
'tax_query' => array(
array(
'taxonomy' => $q->taxonomy,
'terms' => $q->term_id,
'include_children' => false // Exclude child terms
),
array(
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => 'sector1', //I believe this is the slug
),
),
);
EDIT 2
To exclude posts that are in the sector1 tag and any other sectorX tag, you can do the following
You can try something like this: (Requires at least PHP 5.4+. Also, this untested)
$q = get_queried_object();
$args = [
'post_type' => 'sectors',
'tax_query' => [
[
'taxonomy' => $q->taxonomy,
'terms' => $q->term_id,
'include_children' => false // Exclude child terms
],
[
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => 'sector1', //I believe this is the slug
'operator' => 'NOT_IN'
],
],
];
For older PHP versions, use the following
$q = get_queried_object();
$args = array(
'post_type' => 'sectors',
'tax_query' => array(
array(
'taxonomy' => $q->taxonomy,
'terms' => $q->term_id,
'include_children' => false // Exclude child terms
),
array(
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => 'sector1', //I believe this is the slug
'operator' => 'NOT_IN'
),
),
);
Just note, you can pass an array of tags to the terms parameter like this
'terms' => array( 'sector1', 'sector2', 'etc' ),
or short array syntax
'terms' => ['sector1', 'sector2', 'etc'],
EDIT 3
As this is your main query, you need to make a few changes. As I have said, remove the custom query. Your main loop should look something like this
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<a href="<?php echo get_permalink(); ?>">
<?php echo "<div class='col-md-6 col-sm-6 col-xs-12' style='margin-bottom:30px;'>"; ?>
<div class="row mobilemargin">
<div class="categorytiletext2">
<div class="col-md-6 col-sm-12 col-xs-12 nopr"><?php echo get_the_post_thumbnail( $page->ID, 'categoryimage', array('class' => 'hovereffect newimgheight')); ?> </div>
<div class="col-md-6 col-sm-12 col-xs-12 mobilewhite">
<div class="testdiv">
<h5 class="captext"><?php the_title(); ?></h5>
<?php $trimexcerpt = get_the_excerpt();
$shortexcerpt = wp_trim_words( $trimexcerpt, $num_words = 10, $more = '… ' );
echo '<p>' . $shortexcerpt . '</p>';
?>
</div>
</div>
</div>
</div>
<?php echo "</div>"; ?>
</a>
<!-- If there is no posts, display an error message -->
<?php endwhile;
else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>
<!-- If there is no posts, display an error message -->
You can now use pre_get_posts to remove the desired tag from your taxonomy pages. In your functions.php, do the following: (Requires PHP 5.3+, and is also untested)
add_action( 'pre_get_posts', function ( $q )
{
if ( !is_admin() && $q->is_main_query() && $q->is_tax() ) {
$q->set( 'tag__not_in', array( 145 ) );
}
});
For older versions use
add_action( 'pre_get_posts', 'so30256167_remove_tags' );
function so30256167_remove_tags( $q )
{
if ( !is_admin() && $q->is_main_query() && $q->is_tax() ) {
$q->set( 'tag__not_in', array( 145 ) );
}
}
Just remember to change 145 to your exact tag id or an array of tagids
EDIT 4
If you don't have the tag ids, you can use get_term_by() to get the tag id from the tag slug. Something like this will do: (Requires PHP 5.3+, and is also untested)
add_action( 'pre_get_posts', function ( $q )
{
if ( !is_admin() && $q->is_main_query() && $q->is_tax() ) {
$tag_object = get_term_by( 'slug', 'sector1', 'post_tag' );
$tagID = $tag_object->term_id;
$q->set( 'tag__not_in', array( $tagID ) );
}
});
For older versions use
add_action( 'pre_get_posts', 'so30256167_remove_tags' );
function so30256167_remove_tags( $q )
{
if ( !is_admin() && $q->is_main_query() && $q->is_tax() ) {
$tag_object = get_term_by( 'slug', 'sector1', 'post_tag' );
$tagID = $tag_object->term_id;
$q->set( 'tag__not_in', array( $tagID ) );
}
}
If you have an array of tag slugs, you can replace the following
$tag_object = get_term_by( 'slug', 'sector1', 'post_tag' );
$tagID = $tag_object->term_id;
$q->set( 'tag__not_in', array( $tagID ) );/*
with
$tag_array = array( 'slug1', 'slug2', 'slug3' );
foreach ( $tag_array as $tag ) {
$tag_object = get_term_by( 'slug', $tag, 'post_tag' );
$tagids[] = $tag_object->term_id;
}
$q->set( 'tag__not_in', $tagids );
Just remember to change the slugs accordingly
EDIT 5
Your final code in functions.php with pre_get_posts should be
add_action( 'pre_get_posts', 'so30256167_remove_tags' );
function so30256167_remove_tags( $q )
{
if ( !is_admin() && $q->is_main_query() && $q->is_tax() ) {
$tag_array = array( 'sector1', 'sector2', 'sector3', 'sector4' );
foreach ( $tag_array as $tag ) {
$tag_object = get_term_by( 'slug', $tag, 'post_tag' );
$tagids[] = $tag_object->term_id;
}
$q->set( 'tag__not_in', $tagids );
}
}