NextJS dynamic urls query not passing back ID - next.js

I am trying to load data when clicking on a <Link> by passing an ID as a query param. I also need to have a clean URL so I set the "as" option. My problem is that the query param I get back on the loading page is now the value I passed in "as" so I can't use the ID to fetch my data.
Is there an alternative way or something I'm missing?
What I need query param to be is => id = 3
What I'm getting is the slug name => id = "Uncategorized"
<Link key={i} href={{pathname: '/blog/category/[id]', query: {id: cat.category_id}}} as={/blog/category/${cat.category_slug}}>
<a>{cat.category_name}</a>
</Link>

I solved this by fetching all my categories before fetching my posts and matching the category slug with the query.id. I don't know if there is a more nextjs way of doing this but it works for now.

Related

Filter by part of the slug GhostCMS API

I am using NextJS + GhostCMMS and #tryghost/content-api
I want to filter all pages by part of the slug.
For the example, if I have pages - slug1-test, slug2-test, slug3-test, slug4, ...
I want to select all pages with -test at the end of the slug.
Then the result of the example will be:
slug1-test, slug2-test, slug3-test.
This is my code:
const posts = await api.posts.browse({
limit: 10,
include: ['tags', 'count.posts'],
order: ['featured DESC', 'published_at DESC'],
filter: 'slug:[slug1-test]'
})
This code returns a post with a slug slug1-test, because there is a post with exactly that slug, but I need to select, only posts with slug, which includes -test at the end.

WooCommerce, WP all import - Find product ID by attribute value

I want to update WooCommerce products by the WP All import. I have 2 independent xml files (from the first one I'm getting prices, from the second one descriptions). For some reasons product's _sku is {code} from the first one xml not {ean}. So I put {ean} into product attribute pa_ean to match the products from the first one and the second one xml.
Now I don't know how to write the php function to return product_id so WP All import could update right products with right descriptions.
Do you have any unique identifier that are same for the product in both files? Like product_key or something. If you have it you can store it as custom meta for that product and get product by that meta key, something like below ↓
function check_if_product_exist($rawDataFromFile) {
global $products;
// Get WC_Product Objects
$products = wc_get_products([
'meta_key' => 'your_meta_key',
'meta_value' => $rawDataFromFile->your_key
]);
if (!empty($products)) {
return $products[0];
}
return null;
}
I put {ean} to Custom field, not to Attribute and after that I can easily use it in WP All import.

Query string in URL makes main query misbehave and pagination not to work in Wordpress

I have archive page of movies in which I am presenting all movies paginated. On side bar I have genres(taxonomy) for movies. When user clicks on one I want results on the page to be filtered according to which genre he clicked.
My way of thinking made me do this using query string in URL. So when user click on genre it requests same URL (archive for movies) but adds ?genre=SOMETHING. Then in pre_get_posts hook I have this if statement to modify main query:
if(
!is_admin() &&
$query->is_main_query() &&
is_post_type_archive('movie') &&
get_query_var('genre')
)
Then after that I have code like this to filter movies by genre user clicked on :
$taxonomyQuery = [
[
'taxonomy' => 'genre',
'field' => 'slug',
'terms' => get_query_var('genre'),
],
];
$query->set('tax_query', $taxonomyQuery);
Sidebar link are constructed like this :
<a href="<?php echo esc_url(add_query_arg('genre', $genre->slug)) ?>">
<?php echo $genre->name; ?>
</a>
Taxonomy is created with name genre so that name is automatically added to query_vars.
When I open archive page of movies /movies/ I get paginated results and everything works fine. But once I click on genre I get this path /movies/?genre=comedy.
pre_get_posts activates and filters movies according to the genre selected but pagination doesnt work. Even if I set $query->set('posts_per_page', 1); I still get more than one result returned from query. Problem only occurs when query string ?genre=SOMETHING gets added to URL and I cannot figure out why.
NOTE: I am relatively new to wordpress development and I do not actually know if this is the right way to do this kind of thing.
Any help is appreciated!
So after some testing with different things I got to this conclusion.
When I registered taxonomy with register_taxonomy I did not place 'query_var' property as I thought it is adding query string value like when you use :
add_filter('query_vars', 'demo_query_vars');
function demo_query_vars($queryVars) {
$queryVars[] = 'genre';
return $queryVars;
}
These two thing are not the same. First one enables you to load taxonomy using query_var. From the docs :
Sets the query var key for this taxonomy. Default `$taxonomy` key. If false, a taxonomy cannot be loaded at `?{query_var}={term_slug}`. If a string, the query `?{query_var}={term_slug}` will be valid.
Second one enables custom query_var and query string to be used, which is what i needed.
FIX: Just disable query_bar 'query_var' => false'
Then add code I posted above to allow query variable to be processed (add_filter function) and you will be able to use your query_var.
NOTE: This problem was caused for me because I my taxonomy is called genre therfore query_var in register_taxonomy function is automatically set to this value. And I also wanted to use the same name for my own custom query_var which made conflicts.
If your taxonomy name is different from your query_var (the query string you wich to use, example if I used ?g=SOMETHING instead of ?genre=SOMETHING) YOU WILL NOT run into this problem since there will be no conflicts between these two variables..
Another possible solution would be to make your custom query_var different than one specified in register_taxonomy if you are using query_var defined in register_taxonomy function. They just need to be different so there are no conflicts.
I am just at the beginning so this potentially could not be right but it for sure has something to do with these 2 variable names being the same.

Select posts that have a specific term using withSelect in Gutenberg block

I'm trying to select posts -- or more specifically, a custom post type -- that belong to a specific term, and display them in my Gutenberg block's edit screen. I'm wanting to recreate what would be tax_query with WP_Query, but in Javascript.
I'm able to select posts, but I'm unsure what parameters to use with getEntityRecords to select by term (or if it is even possible). The documentation is still a little vague at this point.
Here's where I'm at. This successfully selects all posts of the 'rmenu' type:
const items = select("core").getEntityRecords(
"postType",
"rmenu"
);
Does anyone know if getEntityRecords is the right way to handle this?
Thanks.
The third parameter to getEntityRecords is a query object. You can pass any query argument accepted by Wordpress API such as categories or tags. Selecting by category term would look like this:
const items = select("core").getEntityRecords(
"postType",
"rmenu",
{ categories: [ 13 ] }
}
Although Capi's answer is correct, it wasn't clear for me that this would also work for custom taxonomies. It turns out wp.data will add your custom taxonomies automatically as properties to the post object. For example, a post could look like this:
{
title: "hello world",
content: "this is a post",
id: 123,
type: 'my-custom-posttype'
my-custom-tax: [5, 8, 24],
...
}
So, in order to get all the posts of the type my-custom-posttype that have a term with ID 4 or 8 of the taxonomy my-custom-tax, you would run this query:
wp.data.select( 'core' ).getEntityRecords( 'postType', 'my-custom-posttype', { 'my-custom-tax':[4,8] })
Important! If you test this in your browser, you need to run it twice. The first time it will return an empty array, because it only invokes the promise.

How to get posts of a taxonomy in descending order Corcel Laravel

I'm using Corcel in my Laravel project and I have set my database connection to a wordpress database. I want to get the posts of a taxonomy in descending order according to post_date field. I've developed the following function but it returns the posts in ascending order. How should I change it?
public function posts(Taxonomy $category)
{
return PostResource::collection($category->posts);
}
There is multiple available methods on the Laravel Collection :
https://laravel.com/docs/5.7/collections#available-methods
Try this one :
return PostResource::collection($category->posts)->sortByDesc('post_date');
This method has the same signature as the sortBy method, but will sort the collection in the opposite order.

Resources