
Product
Rust Support Now in Beta
Socket's Rust support is moving to Beta: all users can scan Cargo projects and generate SBOMs, including Cargo.toml-only crates, with Rust-aware supply chain checks.
@nycopportunity/nyco-wp-archive-vue
Advanced tools
Creates a reactive filterable interface for a posts archive.
This Vue.js component creates a reactive filterable interface for a post archive on a WordPress Archive. Uses the WordPress REST API for retrieving filters and posts. Fully configurable for any post type (default or custom). Works with multiple languages using the lang attribute set in on the html tag and the multilingual url endpoint provided by WPML.
This component does not include an HTML template but it can be extended by a parent component and configured with the template, script, and style tags.
Install this dependency in your theme.
npm install @nycopportunity/wp-archive-vue
This example is pulled from the ACCESS NYC WordPress theme. The live example can be seen on access.nyc.gov/programs. It notably uses the Vue.js createElement method and pre-rendering features to avoid the use of unsafe eval() method (creating code from strings) by the application.
It is recommended to register a new REST route that will return the list of terms for the post type that will be queried.
add_action('rest_api_init', function() {
/**
* REST Configuration
*/
/** @var String Namespace for the current version of the API */
$v = 'api/v1';
/** @var Number Expiration of the transient caches */
$exp = WEEK_IN_SECONDS;
/** @var String Language of the request (defined by WPML) */
$lang = (defined('ICL_LANGUAGE_CODE')) ? '_' . ICL_LANGUAGE_CODE : '';
/** @var Array Post types and terms that have corresponding transient caches */
$transients = array(
'programs' => 'rest_terms_json' . $lang
);
/**
* Returns a list of public taxonomies and their terms. Public vs. private
* is determined by the configuration in the Register Taxonomies plugin.
* It is recommended to use the Transients
*/
register_rest_route($v, '/terms/', array(
'methods' => 'GET',
'callback' => function(WP_REST_Request $request) use ($exp, $transients) {
$transient = $transients['programs'];
$data = get_transient($transient);
if (false === $data) {
$data = [];
// Get public taxonomies and build our initial assoc. array
foreach (get_taxonomies(array(
'public' => true,
'_builtin' => false
), 'objects') as $taxonomy) {
$data[] = array(
'name' => $taxonomy->name,
'labels' => $taxonomy->labels,
'taxonomy' => $taxonomy,
'terms' => array()
);
}
// Get the terms for each taxonomy
$data = array_map(function ($tax) {
$tax['terms'] = get_terms(array(
'taxonomy' => $tax['name'],
'hide_empty' => false,
));
return $tax;
}, $data);
set_transient($transient, $data, $exp);
}
$response = new WP_REST_Response($data); // Create the response object
$response->set_status(200); // Add a custom status code
return $response;
}
));
});
Create a proxy module that extends the archive methods and passes any desired configuration. For the sake of this example it can be named my-archive.js.
'use strict';
/**
* This script handles configuration for the Archive.vue component. It
* is scoped to set the post type, initial query, initial headers, endpoints,
* for the post type, and template mappings for filter and post content.
* Template mappings are passed to the Vue Components of the application.
*/
import Archive from 'node_modules/@nycopportunity/wp-archive-vue/src/archive.vue';
export default {
extends: Archive,
props: {
perPage: {
type: Number,
default: 1
},
page: {
type: Number,
default: 5
},
pages: {
type: Number,
default: 0
},
total: {
type: Number,
default: 0
},
paginationNextLink: {type: String},
strings: {type: Object}
},
data: function() {
return {
type: 'programs',
query: {
per_page: this.perPage,
page: this.page
},
headers: {
pages: this.pages,
total: this.total,
link: 'rel="next";'
},
endpoints: {
terms: '/wp-json/api/v1/terms',
programs: '/wp-json/wp/v2/programs'
},
history: {
omit: ['page', 'per_page'],
params: {
'programs': 'categories',
'populations-served': 'served'
}
},
maps: function() {
return {
terms: terms => ({
active: false,
name: terms.labels.archives,
slug: terms.name,
checkbox: false,
toggle: true,
filters: terms.terms.map(filters => ({
id: filters.term_id,
name: filters.name,
slug: filters.slug,
parent: terms.name,
active: (
this.query.hasOwnProperty(terms.name) &&
this.query[terms.name].includes(filters.term_id)
),
checked: (
this.query.hasOwnProperty(terms.name) &&
this.query[terms.name].includes(filters.term_id)
)
}))
}),
programs: p => ({
title: p.acf.plain_language_program_name,
link: p.link,
subtitle: p.acf.program_name + ((p.acf.program_acronym) ?
' (' + p.acf.program_acronym + ')' : ''),
summary: p.acf.brief_excerpt,
category: {
slug: p.timber.category.slug || 'PROGRAMS',
name: p.timber.category.name || 'NAME'
},
icon: p.timber.icon,
status: p.timber.status
})
};
}
};
},
computed: {
/**
* Inserting this computed property into the template hides the server
* rendered content and shows the Vue app content.
*/
initialized: function() {
if (this.init) {
let main = document.querySelector('[data-js="loaded"]');
document.querySelector('[data-js="preload"]').remove();
main.classList.remove('hidden');
main.removeAttribute('aria-hidden');
}
},
categories: function() {
return [this.terms.map(
t => t.filters
.filter(f => f.checked)
.map(f => f.name)
)].flat(2);
}
},
created: function() {
this.getState() // Get window.location.search (filter history)
.queue() // Initialize the first page request
.fetch('terms') // Get the terms from the 'terms' endpoint
.catch(this.error);
}
};
This is where the reactive DOM for your view is added. Import the my-archive.js into your file. For the sake of this example it can be named my-archive.vue.
<template>
<!-- HTML Here -->
</template>
<script>
import MyArchive from 'my-archive.js';
export default MyArchive;
</script>
Finally, import the application and components used to render the data then create the archive element and mount components to it.
/* eslint-env browser */
// Libraries
import Vue from 'vue/dist/vue.runtime.min';
import localize from 'utilities/localize/localize';
// Components
import CardVue from 'components/card/card.vue';
import FilterMultiVue from 'components/filter/filter-multi.vue';
import MyArchive from 'my-archive.vue';
((window, Vue) => {
'use strict';
/**
* Programs Archive
*/
(element => {
if (element) {
/**
* Redirect old filtering method to WP Archive Vue filtering
*/
let query = [];
let params = {
'categories': 'categories[]',
'served': 'served[]'
};
Object.keys(params).forEach(key => {
let datum = element.dataset;
if (datum.hasOwnProperty(key) && datum[key] != '') {
query.push(params[key] + '=' + datum[key]);
}
});
if (query.length) window.history.replaceState(null, null, [
window.location.pathname, '?', query.join('')
].join(''));
/**
* Get localized strings from template
*/
let strings = Object.fromEntries([
'ARCHIVE_TOGGLE_ALL', 'ARCHIVE_LEARN_MORE', 'ARCHIVE_APPLY',
'ARCHIVE_ALL', 'ARCHIVE_PROGRAMS', 'ARCHIVE_FILTER_PROGRAMS',
'ARCHIVE_NO_RESULTS', 'ARCHIVE_SEE_PROGRAMS', 'ARCHIVE_LOADING',
'ARCHIVE_NO_RESULTS_INSTRUCTIONS', 'ARCHIVE_MORE_RESULTS'
].map(i => [
i.replace('ARCHIVE_', ''),
localize(i)
]));
/**
* Add Vue components to the vue instance
*/
Vue.component('c-card', CardVue);
Vue.component('c-filter-multi', FilterMultiVue);
/**
* Pass our configuration options to the Archive method (including Vue)
*/
new Vue({
render: createElement => createElement(MyArchive, {
props: {
perPage: parseInt(element.dataset.perPage),
page: parseInt(element.dataset.page),
pages: parseInt(element.dataset.pages),
total: parseInt(element.dataset.count),
paginationNextLink: element.dataset.paginationNextLink,
strings: strings
}
})
}).$mount(`[data-js="${element.dataset.js}"]`);
}
})(document.querySelector('[data-js="programs"]'));
})(window, Vue);
The Mayor's Office for Economic Opportunity (NYC Opportunity) is committed to sharing open source software that we use in our products. Feel free to ask questions and share feedback. Interested in contributing? See our open positions on buildwithnyc.github.io. Follow our team on Github (if you are part of the @cityofnewyork organization) or browse our work on Github.
FAQs
Creates a reactive filterable interface for a posts archive.
We found that @nycopportunity/nyco-wp-archive-vue demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket's Rust support is moving to Beta: all users can scan Cargo projects and generate SBOMs, including Cargo.toml-only crates, with Rust-aware supply chain checks.
Product
Socket Fix 2.0 brings targeted CVE remediation, smarter upgrade planning, and broader ecosystem support to help developers get to zero alerts.
Security News
Socket CEO Feross Aboukhadijeh joins Risky Business Weekly to unpack recent npm phishing attacks, their limited impact, and the risks if attackers get smarter.