I've created an option tab with Advanced Custom fields where you can paste your Google Maps API key, so I don't have to put the API key in the code over and over again when starting a new project.
Get the value of the custom field where I put my API key:
$mapsApi = get_field('maps_api', 'option');
Now, I am loading the API key with the following script:
function bredweb_files() {
// scripts
wp_enqueue_script('maps-api', 'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY', array(), '1', true);
}
add_action( 'wp_enqueue_scripts', 'bredweb_files' );
(That is of course not the only thing I'm loading, also styles and other scripts)
So my question is, how do I place that variable ($mapsApi) in the url, instead of the YOUR_API_KEY?
I've tried the obvious: https://maps.googleapis.com/maps/api/js?key=$mapsApi, yet that doesn't work.
You can do such type of things.
function bredweb_files() {
$mapsApi = get_field('maps_api', 'option');
wp_enqueue_script('maps-api', 'https://maps.googleapis.com/maps/api/js? key='.$mapsApi, array(), '1', true);}
add_action( 'wp_enqueue_scripts', 'bredweb_files' );
Related
I want to expose all the ACF fields that belong to a page or custom post type to the WordPress REST API in order to do some API calls through javascript.
The final expected result would be all the ACF fields inside an ACF object that you can easily access.
Another simple solution that is working perfect for me now.
You can add the following function on functions.php or fields.php
Using ACF getFields before sending a rest request. You can add this to any special page rest_prepare_page or rest_prepare_post.
The ACF data will be in the json response with key acf
// add this to functions.php
//register acf fields to Wordpress API
//https://support.advancedcustomfields.com/forums/topic/json-rest-api-and-acf/
function acf_to_rest_api($response, $post, $request) {
if (!function_exists('get_fields')) return $response;
if (isset($post)) {
$acf = get_fields($post->id);
$response->data['acf'] = $acf;
}
return $response;
}
add_filter('rest_prepare_post', 'acf_to_rest_api', 10, 3);
Through the following code, you will be able to expose page and your custom postypes ACF fields in the wordpress REST API and access them inside the ACF object.
You can obviously customise the postypes to exclude or to include in the arrays: $postypes_to_exclude and $extra_postypes_to_include.
function create_ACF_meta_in_REST() {
$postypes_to_exclude = ['acf-field-group','acf-field'];
$extra_postypes_to_include = ["page"];
$post_types = array_diff(get_post_types(["_builtin" => false], 'names'),$postypes_to_exclude);
array_push($post_types, $extra_postypes_to_include);
foreach ($post_types as $post_type) {
register_rest_field( $post_type, 'ACF', [
'get_callback' => 'expose_ACF_fields',
'schema' => null,
]
);
}
}
function expose_ACF_fields( $object ) {
$ID = $object['id'];
return get_fields($ID);
}
add_action( 'rest_api_init', 'create_ACF_meta_in_REST' );
Here's the gist for reference: https://gist.github.com/MelMacaluso/6c4cb3db5ac87894f66a456ab8615f10
You can use the following plugin to expose the ACF fields in REST.
https://wordpress.org/plugins/acf-to-rest-api/
If your ACF fields have a relationship and want to include those relationships in rest as well, you can use the following plugin.
https://github.com/airesvsg/acf-to-rest-api-recursive
ACF has the ability to have fields added to the REST API via each field as of version 5.11. You can review the update here: https://www.advancedcustomfields.com/resources/rest-api/
The gist is that each field has a setting for "Show in REST API". By default it is set to "No", but if you switch this to "Yes" it will be added to the REST data for each post/custom post type.
Task:
To allow CMS users to change the image used when sharing a post to Twitter. Yoast uses the Featured Image when creating the Twitter Card.
The approach:
Add a custom meta field to posts. Extend the WPSEO_Twitter class and or just the private function output_metatag(). If the custom meta field is not empty, use the custom field value instead of the default.
Code:
if (class_exists('WPSEO_Twitter')) :
remove_action( 'wpseo_head', array( 'WPSEO_Twitter', 'get_instance' ), 40 );
add_action( 'wpseo_head', array( 'EXAMPLE_WPSEO_Twitter', 'get_instance' ), 40 );
class EXAMPLE_WPSEO_Twitter extends WPSEO_Twitter {
// etc
}
endif;
Issues:
The remove_action isn't working and the twitter meta code is being duplicated. The plugin's class and my extended class are both being executed.
Links: https://github.com/Yoast/wordpress-seo/blob/trunk/frontend/class-twitter.php
I think it would be easier to add a filter to wpseo_twitter_image that changes the image to what you desire.
Something along the lines of
add_filter("wpseo_twitter_image", function($img) {
if($myimg = get_post_meta(get_the_ID(), "custom-twitter-image", true)) {
return $myimg;
}
return $img;
});
should probably work for you, if I understood you correctly.
My Wordpress site uses custom template pages like this one:
<php
/*
Template Name : project_costs
/*
get_header ();
// set default vars or user received
require("my_forms.php");
// pull data from db and calculate
require("project_calculation. php");
// create page
require("content. php");
...
My custom page project_costs.php performing the steps :
Receive and set user entered vars from page forms (POST/GET).
Pull data from database.
Do some calculations and changes.
Creates page for user.
I want to integrate angular.js with the WP-API plugin. The plugin just pulls raw data from database (step 2) and sends it to front end (step 4). So pages and templates not in use as page didn't reload.
I want to pass data to my php class first (step 3), then pass changed data to WP-API.
Is there any function in WP-API to call my PHP file or function?
Any advice, samples or links would be highly appreciated.
Thanks.
So I'm working on a huge project which includes several API/Angular replacement parts for #WordPress. One file is a custom endpoint-boilerplate.php. It works like a charm so far but any input would be appreciated.
Just follow the structure and use the my_awesome_function to return do anything you'd like. Then the namespace and route from the hook will be available, using data from my_awesome_func.
<?php
/* ------------------------------------------------------------------------ *
A great example of custom endpoints is the PHP in wp-api-menus plugin
* ------------------------------------------------------------------------ */
// hook into rest_api_init and register a new api route
add_action( 'rest_api_init', function () {
register_rest_route(
'custom-endpoint/v2', // namespace
'/author/(?P<id>\d+)', // route
array( // options
'methods' => 'GET',
'callback' => 'my_awesome_func',
// 'args' => array(
// 'context' => array(
// 'default' => 'view',
// ),
// )
)
);
});
function my_awesome_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if ( empty( $posts ) ) {
return null;
}
return $posts[0]->post_title;
}
So your call will then be a get to http://yourproject.com/wp-json/custom-endpoint/v2/author/1
So I want to include fusion builder's post editor on some custom post types that I've created. There is a fix to this go to fusion-core > admin > class-pagebuilder.php and edit line 53.
var $allowed_post_types = array('page','post','avada_faq','avada_portfolio', 'add my custom types here');
But anytime there is an update this will be deleted and I'd like to not have to worry about this, or worry about it! So is there anyway i can create a plugin helper, or add something to my functions.php file that wont get replaced every time there is an update.
the instance is create line 22 of the file fusion-core.php
so to overide this, you can try something like this :
add_action ("plugins_loaded", function () {
// unregister habitual call
remove_action( 'plugins_loaded', array( 'Fusion_Core_PageBuilder', 'get_instance' ) );
// call of the instance
// you have to change the path of the fusion-core plugin
if( ! get_option( 'avada_disable_builder' ) ) {
if ( is_admin() ) {
require_once( path of the fusion-core plugin . 'admin/class-pagebuilder.php' );
$instance = Fusion_Core_PageBuilder::get_instance();
$instance->allowed_post_types[] = "custom post type";
}
}
}, 9); // priority 9 to be called before the line of fusion-core.php
For me, I found that there was no need to remove the action...and in fact, it did not work when I did so. Instead, I simply called the same action and changed the values. I also found that I only needed the "UI instance". Here's what worked for me. I've now added the page builder successfully to ten different post types on my site see below:
if ( is_admin() ) {
require_once('path to plugin directory/fusion-core/admin/class-pagebuilder.php' );
require_once('path to plugin directory/fusion-core/admin/page-builder/classes/class-ui.php' );
$ui = Fusion_Core_PageBuilder_UI::get_instance();
$ui->settings['allowed_post_types'][] = 'your_custom_post_type';
}
I am having trouble trying to pass an extra variable in the url to my WordPress installation.
For example /news?c=123
For some reason, it works only on the website root www.example.com?c=123 but it does not work if the url contains any more information www.example.com/news?c=123. I have the following code in my functions.php file in the theme directory.
if (isset($_GET['c']))
{
setcookie("cCookie", $_GET['c']);
}
if (isset($_SERVER['HTTP_REFERER']))
{
setcookie("rCookie", $_SERVER['HTTP_REFERER']);
}
Any Ideas?
To make the round trip "The WordPress Way" on the "front-end" (doesn't work in the context of wp-admin), you need to use 3 WordPress functions:
add_query_arg() - to create the URL with your new query variable ('c' in your example)
the query_vars filter - to modify the list of public query variables that WordPress knows about (this only works on the front-end, because the WP Query is not used on the back end - wp-admin - so this will also not be available in admin-ajax)
get_query_var() - to retrieve the value of your custom query variable passed in your URL.
Note: there's no need to even touch the superglobals ($_GET) if you do it this way.
Example
On the page where you need to create the link / set the query variable:
if it's a link back to this page, just adding the query variable
<a href="<?php echo esc_url( add_query_arg( 'c', $my_value_for_c ) )?>">
if it's a link to some other page
<a href="<?php echo esc_url(
add_query_arg( 'c', $my_value_for_c, site_url( '/some_other_page/' ) )
)?>">
In your functions.php, or some plugin file or custom class (front-end only):
function add_custom_query_var( $vars ){
$vars[] = "c";
return $vars;
}
add_filter( 'query_vars', 'add_custom_query_var' );
On the page / function where you wish to retrieve and work with the query var set in your URL:
$my_c = get_query_var( 'c' );
On the Back End (wp-admin)
On the back end we don't ever run wp(), so the main WP Query does not get run. As a result, there are no query vars and the query_vars hook is not run.
In this case, you'll need to revert to the more standard approach of examining your $_GET superglobal. The best way to do this is probably:
$my_c = filter_input( INPUT_GET, "c", FILTER_SANITIZE_STRING );
though in a pinch you could do the tried and true
$my_c = isset( $_GET['c'] ) ? $_GET['c'] : "";
or some variant thereof.
There are quite few solutions to tackle this issue. First you can go for a plugin if you want:
WordPress Quickie: Custom Query String Plugin
Or code manually, check out this post:
Passing Query String Parameters in WordPress URL
Also check out:
add_query_arg
Since this is a frequently visited post i thought to post my solution in case it helps anyone. In WordPress along with using query vars you can change permalinks too like this
www.example.com?c=123 to www.example.com/c/123
For this you have to add these lines of code in functions.php or your plugin base file.
From shankhan's anwer
add_filter( 'query_vars', 'addnew_query_vars', 10, 1 );
function addnew_query_vars($vars)
{
$vars[] = 'c'; // c is the name of variable you want to add
return $vars;
}
And additionally this snipped to add custom rewriting rules.
function custom_rewrite_basic()
{
add_rewrite_rule('^c/([0-9]+)/?', '?c=$1', 'top');
}
add_action('init', 'custom_rewrite_basic');
For the case where you need to add rewrite rules for a specifc page you can use that page slug to write a rewrite rule for that specific page. Like in the question OP has asked about
www.example.com/news?c=123 to www.example.com/news/123
We can change it to the desired behaviour by adding a little modification to our previous function.
function custom_rewrite_basic()
{
add_rewrite_rule('^news/([0-9]+)/?', 'news?c=$1', 'top');
}
add_action('init', 'custom_rewrite_basic');
Hoping that it becomes useful for someone.
add following code in function.php
add_filter( 'query_vars', 'addnew_query_vars', 10, 1 );
function addnew_query_vars($vars)
{
$vars[] = 'var1'; // var1 is the name of variable you want to add
return $vars;
}
then you will b able to use $_GET['var1']
<?php
$edit_post = add_query_arg('c', '123', 'news' );
?>
Go to New page
You can add any page inplace of "news".
One issue you might run into is is_home() returns true when a registered query_var is present in the home URL. For example, if http://example.com displays a static page instead of the blog, http://example.com/?c=123 will return the blog.
See https://core.trac.wordpress.org/ticket/25143 and https://wordpress.org/support/topic/adding-query-var-makes-front-page-missing/ for more info on this.
What you can do (if you're not attempting to affect the query) is use add_rewrite_endpoint(). It should be run during the init action as it affects the rewrite rules. Eg.
add_action( 'init', 'add_custom_setcookie_rewrite_endpoints' );
function add_custom_setcookie_rewrite_endpoints() {
//add ?c=123 endpoint with
//EP_ALL so endpoint is present across all places
//no effect on the query vars
add_rewrite_endpoint( 'c', EP_ALL, $query_vars = false );
}
This should give you access to $_GET['c'] when the url contains more information like www.example.com/news?c=123.
Remember to flush your rewrite rules after adding/modifying this.
to add parameter to post urls (to perma-links), i use this:
add_filter( 'post_type_link', 'append_query_string', 10, 2 );
function append_query_string( $url, $post )
{
return add_query_arg('my_pid',$post->ID, $url);
}
output:
http://yoursite.com/pagename?my_pid=12345678
This was the only way I could get this to work
add_action('init','add_query_args');
function add_query_args()
{
add_query_arg( 'var1', 'val1' );
}
http://codex.wordpress.org/Function_Reference/add_query_arg
In your case, Just add / after url and then put query arguments. like
www.example.com/news/?c=123 or news/?c=123
instead of
www.example.com/news?c=123 or news?c=123