I simply want to add a field to all my products on woocommerce which isn't visible to customers.
This will be useful when exporting the product list to csv and calculating based on this value later.
Probably overlooked something obvious.
Thanks in advance.
First, you need to get all of your products. After that, check this meta key is already exists. If yes, then update the value; otherwise, add it as a new meta key.
<?php
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
);
$products = new WP_Query( $args );
while ( $products->have_posts() ) : $products->the_post();
if(!empty(get_post_meta($post->ID, '_your_custom_meta_key', true))){
update_post_meta($post->ID, '_your_custom_meta_key', 'Your custom value');
}else{
add_post_meta($post->ID, '_your_custom_meta_key', 'Your custom value');
}
endwhile;
wp_reset_query();
?>
Related
I have created an ACF field where I can add 1 keyword per post. I want to get now a list of all keywords set in all my posts and sort it by alphabet and add a link to the post where it was found. Every keyword will be unique. So it would be a kind of table of content. How can I do that programatically? I have no idea right now on how to loop through posts and get field values.
Place the following function in functions.php . Use it directly in your template or as shortcode or w/e
function keywords_post_list() {
//We build our query for posts containing any value in meta field
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'meta_query' => array(
'key' => 'keyword', //change with your meta key
'value' => '',
'compare' => '!='
)
);
$query = new WP_Query($args);
global $post;
$items = array();
if($query->have_posts()):
while($query->have_posts()):
$query->the_post();
//Looping each post we collect the keyword and the link for a post.
//Grab any other information if you need and add in the array
$keyword = get_post_meta($post->ID,'keyword',true);
$link = get_the_permalink($post->ID);
//Our array
$items[] = array('keyword'=> $keyword,'link' => $link);
endwhile;
endif;
// We need to sort results by keyword currently ASC
array_multisort(array_column($items, 'keyword'), $items);
// If we need to sort DESC uncommnet bellow coment above
// array_multisort(array_column($items, 'keyword'),SORT_DESC, $items);
// error_log(print_r($items,true));
if($items):
echo '<ol class="keyword-list">';
foreach($items as $item):
$keyword = $item['keyword'];
$link = $item['link'];
echo '<li>'.$keyword.'</li>';
endforeach;
echo '</ol>';
endif;
}
I want to create a loop and query posts by their author role. And display the results of a search term based on the authors role.
I've tried creating a function to alter the query's where clause:
$ids = get_users(
array(
'role' => 'administrator' ,
'fields' => 'ID'
)
);
$query = new WP_Query(
array(
'author__in' => $ids,
)
);
// If the query has data
if($query->have_posts() ) :
// Post loop
while ($query->have_posts() ) :
// Setup post data
$query->the_post();
?>
<!-- Do HTML markup and template tags here, eg. the_content(), the_title() etc.. -->
<h1>You're a post from administrator - <?php the_title(); ?></h1>
<?php get_template_part( 'template-parts/content', 'search' ); ?>
<?php
endwhile;
// End "If the query has data"
endif;
I'm trying to add a WP_Query to the loop but this is where I get stuck with the results not getting filtered by role so I'm fairly certain I must be implementing this wrong - this is the first time I've tried to do something like this so sorry if it's a dump question but I can't find an answer to my question so if anyone can point me in the right direction that would be amazing!
Any advice welcome, thank you!
You can try the posts_where
hook.
UPDATE:
Why don't you use the default WP_Query author arg instead hook.
You query will be :
$ids = get_users(
array(
'role' => 'administrator' ,
'fields' => 'ID'
)
);
$query = new WP_Query(
array(
'author__in' => $ids,
)
);
I am trying to retrieve all advanced custom fields tied to a particular page. This is different than iterating through posts, I am familiar with the following:
$posts = get_posts(array(
'post_type' => 'post_name',
'meta_key' => 'color',
'meta_value' => 'red'
));
However this method is specific to posts and does not allow me to retrieve all ACF by page name.
I appreciate any suggestions on how to accomplish this.
The are too ways to do this that come to mind...
1. Using the Loop
Using WP_Query you can do something like this...
<?php
// WP_Query arguments
$args = array (
'pagename' => 'homepage',
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
the_field( "field_name" );
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
?>
In place of the 'homepage' in 'pagename' => 'homepage', you want to put the page slug of your page. And of course in place of the_field( "text_field" ); you want to add your fields/content.
You can also query by Page ID and some other parameters. You can find all other parameters that you can use here:
https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters
2. Adding second parameter to the_field() function
More simple way, without custom loop, is just to use ACF's built-in the_field() function with the $post->ID parameter added as a second parameter.
<?php the_field('field_name', 123);
This might be the way to go since you want to show the content of only one page, and therefore don't really need to loop.
Reference: http://www.advancedcustomfields.com/resources/how-to-get-values-from-another-post/
You can use ACF's get_fields() function -
<?php $fields = get_fields( $post->ID ); ?>
You could then loop through them or simply print the array for testing.
http://www.advancedcustomfields.com/resources/get_fields/
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.
I have made a custom field "checkbox". I want to exclude posts only that have the checkbox checked.
I am not able to do so.
Here is the code that i am using
$args = array(
'posts_per_page'=> -1,
'post_type' => 'latestnews',
'orderby'=> 'id',
'meta_key'=>'',
'meta_value'=>'',
'order'=> 'asc',
);
query_posts($args);
$my_posts = new WP_Query($args);
So basically i want the posts only that doesn't have the meta key "sticky" set and meta value does not exists.
here my meta key is a checkbox and the value yes is stored in the database if i check the checkbox and nothing is stored in the database if i do not check the option.
<?php
$check_metakey = get_post_meta($post->ID, "sticky", true);
if($check_metakey !== '') :
?>
your article's template
<?php
endif;
?>
NOTE: All this INSIDE the while cycle.
Good luck! :)