GithubHelp home page GithubHelp logo

robbertdk / wordpress-ajax-filter-posts Goto Github PK

View Code? Open in Web Editor NEW
24.0 4.0 11.0 128 KB

A WordPress plugin to filter posts with taxonomies terms and load more posts via Ajax

License: GNU General Public License v2.0

PHP 53.08% CSS 22.50% JavaScript 24.42%

wordpress-ajax-filter-posts's Introduction

WordPress Ajax Filter Posts

Description

A WordPress plugin to filter posts with taxonomies terms and load more posts via Ajax. You can add posts and filters via a shortcode on any page.

[ajax_filter_posts post_type="recipe" tax="meal_type, food_type, diet_type"  posts_per_page="12"]

This plugins uses no dependencies, is translatable and WPML ready.

Parameters

  • tax A comma seperated list of taxonomies to filter the post by. Default post_term.

  • post_type A comma seperated list of post types to show. Default post.

  • post_status A comma seperated list of post status to show. Default publish.

  • post_per_page Numbers of maximum posts to retreive at a time. Default 12.

  • orderby Value to order the posts by. Supports ID, author, title, name, type, date, modified, parent, rand, comment_count, relevance, and menu_order. Does not support meta_value, meta_value_num, post_name__in, post_parent__in post_parent__in because additionals arguments needs to be set with these orderby values. You can add your own query arguments via a filter hook if you need that support. Defaults to date.

    Check the WordPress documentation on Query arguments for more information.

  • order Order the posts ascending or descendings. Support ASC (1, 2, 3; a, b, c) and DESC (3, 2, 1; c, b, a). Defaults to DESC.

  • multiselect Allow one or more active filters per taxonomy. Defaults to true: allow more active filters

  • id Usefull for custom styling or to target specific instances of the shortcode in the filter hooks. Default not set.

Overwriting template files

To easily overwrite template files you can copy one or more of the files in the templates folder to your own theme. Create a folder ajax-filter-posts in the root of your theme directory and copy the files in that newly created folder. Keep in mind that you have to keep the folder structure intact. For example: If you want a custom version of loop.php, you copy the file to <<your-public-folder>>/wp-content/themes/<<your-theme>>/ajax-filter-posts/partials.

You can also set a custom template path.

Motivation

I build a lot of sites that needed a functionality like this and decided to create a plugin for it. Although there are a lot of plugins doing something like this, they usually add a lot of bloat and are not developer friendly. This plugin is for a developer easier to implement, easier to edit and keeps te codebase cleaner.

Installation

Clone this repo to your plugins or mu-plugins folder. When you load it in your mu-plugins folder, you have to call the plugin via a file that is directly in the mu-plugins folder. See this article for more information.

Requirements

Wordpress 5.7.0 or higer

Filters hooks

As a developer you can overwrite functionality with WordPress hooks

ajax_filter_posts_query_args

Description

With the filter ajax_filter_posts_query_args you can pass or alter query arguments to all post queries made by this plugin.

Arguments

array $query_args - query arguments set by the plugin Ajax Filter posts array $shortcode_attributes - all shortcode attributes

Example

For example you can add an extra taxonomy query.

/**
 * Add the diet term on all the queries made with the shortcode ajax_filter_posts
 *
 * @param array $query_args 			query arguments set by the plugin Ajax Filter posts
 * @param array $shortcode_attributes 	all shortcode attributes
 *
 * @return array a updated list of query arguments
 */
function my_site_set_additional_term_for_ajax_filter_posts($query_args, $shortcode_attributes) {

	// Only show posts with the term vegan in the diet taxonomy
	$diet_tax_query_args = [
		[
			'taxonomy' => 'diet',
			'field'    => 'slug',
			'terms'    => 'vegan',
		],
	];

	// If there are already tax queries args set, merge my query args with the set args
	if ( !empty( $query_args['tax_query'] ) ) {
		$prev_set_tax_args = $query_args['tax_query'];
		$query_args['tax_query'] = [
			// Set the relationship to AND: we want only post with my term and the set terms by the user
      		// Also see https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters
			'relation' => 'AND',
			$diet_tax_query_args,
			$prev_set_tax_args
		];
		return $query_args;
	}

	// If there are no tax queries args already set, just add it
	$query_args['tax_query'] = $diet_tax_query_args;
	return $query_args;
}
add_filter('ajax_filter_posts_query_args', 'my_site_set_additional_term_for_ajax_filter_posts', 10, 2);

ajax_filter_posts_is_post_type_viewable

By default only post types that are publicly queryable are allowed as shortcode parameters. This prevents that for example a custom private can be viewed when the wrong parameters are set or when a visitor manipulates the AJAX-request.

For built-in post types such as posts and pages, the 'public' value will be evaluated. For all others, the 'publicly_queryable' value will be used.

You can overwrite this check with this hook

Arguments

boolean $is_publicly_queryable - Default return value, esult of checking all set post types against Wordpress' is_post_type_viewable function

array $shortcode_attributes - all shortcode attributes, including the post_type attribute

ajax_filter_posts_is_post_status_viewable

By default only post status that are publicly queryable are allowed as shortcode parameters. This prevents that for example private or trashed posts can be viewed when the wrong parameters are set or when a visitor manipulates the AJAX-request.

For built-in post statuses such as publish and private, the ‘public’ value will be evaluted. For all others, the ‘publicly_queryable’ value will be used.

You can overwrite this check with this hook

Arguments

boolean $is_publicly_queryable - Default return value, result of checking all set post status against Wordpress' is_post_status_viewable function

array $shortcode_attributes - all shortcode attributes, including the post_status attribute

ajax_filter_posts_template_name

This package searches for the the template files in the active theme folder and in this plugin folder. If that doesn't fit your needs, you can overwrite the template path.

Arguments

string $template - The current retrieved template path. Empty if no path could be found.

string $template_name - The name of the current template to retrieve, with exentsion and subpath (e.g. base.php, partials/filters.php). See the template folder of this package for the used template files.

Arguments

boolean $is_publicly_queryable - Default return value, result of checking all set post status against Wordpress' is_post_status_viewable function

array $shortcode_attributes - all shortcode attributes, including the post_status attribute

License

GNU GENERAL PUBLIC LICENSE

wordpress-ajax-filter-posts's People

Contributors

ians88 avatar lud avatar robbertdk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

wordpress-ajax-filter-posts's Issues

Accessibillity could be better

  1. Convert the filter list to form elements, because in essence, that is what they are.
  2. Add ARIA live region to announce filter updates
  3. Add rel="next" to the load more button

Load more

How can we load more data ON SCROLL by disabling: on(container, 'click', '.js-load-more', function(event) {
Thank you

Issue loading posts

First off, thank you for creating this plugin- it looks to do exactly what I need for a current project. I'm experiencing an issue with the posts not loading, however, when clicking on filters. On my template page, using the shortcode, I can see the filters and posts rendered on the page, but when I click on one of the terms to filter posts, it just hangs with the animation and I see in the console:

Failed to load resource: the server responded with a status of 500 (Internal Server Error) ajax-filter-posts.js?ver=4.8:193 (index):1 Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at XMLHttpRequest.request.onload (ajax-filter-posts.js?ver=4.8:200)

Do you know what might be happening here?

Trigger filter selection with hash url

Hi, it's me again :)

I wanted to use url to select a filter when opening the page with the hash.
Ex: when accessing to https://my-website.com/#filter=apple, the ajax filter for "apple" would be automatically applied.

I almost managed to do it, except that, after loading the page through the url hash, when I clicked from one filter to another the ajax requests were duplicated, so the results were not good, I couldn't figured out why.

I don't have time to look into it anymore but I think it could be a good feature !

Hook to override template

Hello,

I’m using Oxygen Builder who removes WP template system so I'd like to overwrite templates with a custom plugin (like that https://wpdevdesign.com/how-to-override-woocommerce-templates-using-a-custom-functionality-plugin/ ).

I don't think there is a hook to do that in your plugin, but some plugins give us the possibility to do that like woocommerce :

https://github.com/woocommerce/woocommerce/blob/77917a2de31d76f90b4380815a48b4efcef543a8/plugins/woocommerce/includes/wc-core-functions.php#L289

Is it possible to implement a hook like that ?

Thanks

See all terms even if there is no product linked to one of them

Hi,

this is not really an issue but, I wanted to know if it's possible to display all terms even if there is 0 product in one of them.
Currently, if a term is not "linked" with any product, it does not appear in my filter.

Can you tell me if there is a way to do this ? (I couldn't find a hook or something to do this).

Thanks,
Quentin

Post status

Hi, is it possible to add the post_status in query args ?
Thanks for your answer !

Clear button

Hi,

Thank you for this really nice plugin. I was wondering myself if there was a way to add a "Clear" button which would reset all applied filters ?

Thanks a lot,
David

meta key

could you show an example of adding to the filter meta key value?
e.g. input price and posts are filtered with an exact match value price

Initiate the plugin without the use of a shortcode

When you want to use this plugin directly in your theme files you have to write something like <?php echo do_shortcode('[ajax_filter_posts post_type="posts" tax="post_category," posts_per_page="16"]', false ); ?> It would be nice if you can initiate as a function, something like

<?php echo ajax_filter_posts([
   'post_type' => 'posts',
   'taxonomy' => 'post_category',
   'posts_per_page' => 16,
]); ?>

Or maybe even break it up into several shortcodes and functions, as Facet WP does.

Remove opinionated styling: more focus on the core concept of this plugin AJAX fetching and filtering

This plugin includes a lot of specific styling. Although it's easy to remove the styling, I like a more bare bones approach. The idea of this plugin is that it would be easy for theme authors to add an ajax filter and pagination functionality to the theme without the hassle of setting up the AJAX fetching and the filtering, not providing a fully designed filter plugin.

From that point of view the styling is redundant and anoying.

JSON Parse error

UPDATE
This issue was due to Polylang plugin, after deactivate it, everything worked correctly. I tried Loco Translate and everything seems ok now.

Hi,
I just found your awesome plugin and tried it but there is a JSON parse error when trying to load more or filter my posts.

Here the console log error :

Uncaught SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at XMLHttpRequest.request.onload (ajax-filter-posts.js?ver=4.9.6:200)

I changed the line 188 in ajax-filter-posts.js :
request.setRequestHeader("Content-Type", "text/plain");

It seems to be working, but I'm not sure if it's ok and secondly, a load more or filter request now return a 400 Bad Request error:

POST http://skald/wp-admin/admin-ajax.php 400 (Bad Request)

getAJAXPosts @ ajax-filter-posts.js?ver=4.9.6:230
handleFilterEvent @ ajax-filter-posts.js?ver=4.9.6:84
(anonymous) @ ajax-filter-posts.js?ver=4.9.6:24
(anonymous) @ ajax-filter-posts.js?ver=4.9.6:264
ajax-filter-posts.js?ver=4.9.6:193

0

I don't know if you're still updating this plugin, but is there a way to help me with that ?

Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.