Created
June 21, 2023 01:27
-
-
Save everaldomatias/7d309fd83481632dfc722afcadf0c905 to your computer and use it in GitHub Desktop.
Implementa chart.js no WP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function custom_endpoint_init() { | |
register_rest_route( 'meusite/v1', '/graficos/', array( | |
'methods' => 'GET', | |
'callback' => 'minha_funcao_de_resposta', | |
'args' => array( | |
'meta' => array( | |
'validate_callback' => function($param, $request, $key) { | |
return is_string( $param ); | |
} | |
), | |
'posts_per_page' => array( | |
'validate_callback' => function($param, $request, $key) { | |
return is_numeric( $param ); | |
} | |
), | |
), | |
) ); | |
} | |
add_action( 'rest_api_init', 'custom_endpoint_init' ); | |
function minha_funcao_de_resposta( $data ) { | |
$metas = explode(',', $data['meta']); | |
$meta_query = array(); | |
foreach($metas as $meta){ | |
$key_value = explode(':', $meta); | |
$meta_query[] = array( | |
'key' => $key_value[0], | |
'value' => $key_value[1], | |
'compare' => '=', | |
); | |
} | |
$args = array( | |
'post_type' => 'dado', | |
'posts_per_page' => isset($data['posts_per_page']) ? $data['posts_per_page'] : '10', | |
'meta_query' => $meta_query, | |
); | |
$query = new WP_Query( $args ); | |
$posts = array(); | |
if ( $query->have_posts() ) { | |
while ( $query->have_posts() ) { | |
$query->the_post(); | |
$posts[] = array( | |
'id' => get_the_ID(), | |
'uf' => get_post_meta(get_the_ID(), 'uf', true), | |
'cidade' => get_post_meta(get_the_ID(), 'cidade', true), | |
'area_de_atuacao' => get_post_meta(get_the_ID(), 'area_de_atuacao', true), | |
); | |
} | |
} | |
wp_reset_postdata(); | |
if ( empty( $posts ) ) { | |
return new WP_Error( 'no_posts', 'Não foi encontrado nenhum post com este parametro', array( 'status' => 404 ) ); | |
} | |
return $posts; | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
include plugin_dir_path( __FILE__ ) . 'includes/endpoint.php'; | |
function load_scripts() { | |
// Substitua 'caminho/para/chart.min.js' pelo caminho real para o arquivo chart.min.js em seu diretório de plugins. | |
wp_enqueue_script('chartjs', plugin_dir_url(__FILE__) . 'assets/js/chart.min.js', array(), '3.6.2', true); | |
} | |
add_action('wp_enqueue_scripts', 'load_scripts'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment