How do I create a custom api endpoint? - wordpress

I am new to WordPress plugin development. I currently am trying to develop an addition calculator plugin which has the API endpoint at example.com/calc/add. How would I add a new URL endpoint to my WordPress installation so the plugin can take in 'POST' requests (numbers in a comma-separated list) and return the data accordingly after adding the numbers? Thank you so much!

You can use parse_request hook for creating end point, below is the example from one of my plugin
// this example creates endpoint like http://emerico.in/api/v2
add_action('parse_request', 'endpoint', 0);
add_action('init', 'add_endpoint');
/**
* #param null
* #return null
* #description Create a independent endpoint
*/
function endpoint()
{
global $wp;
$endpoint_vars = $wp->query_vars;
// if endpoint
if ($wp->request == 'api/v2') {
// Your own function to process end pint
$this->processEndPoint($_REQUEST);
// After all redirect to home page
wp_redirect(home_url());
exit;
} elseif (isset($endpoint_vars['tracking']) && !empty($endpoint_vars['tracking'])) {
$request = [
'tracking_id' => $endpoint_vars['tracking']
];
$this->processEndPoint($request);
} elseif (isset($_GET['utm_source']) && !empty($_GET['utm_source'])){
$this->processGoogleTracking($_GET);
}
}
/**
* #param null
* #return null
* #description Create a permalink endpoint for projects tracking
*/
function add_endpoint()
{
add_rewrite_endpoint('tracking', EP_PERMALINK | EP_PAGES, true);
}

Minimal code
This creates the custom-endpoint like so http://example.com/custom-endpoint.
add_action('parse_request', 'register_endpoint', 0);
function register_endpoint() {
global $wp;
if ($wp->request == 'custom-endpoint') {
echo 'hello world'; // process anything here
exit;
}
}

Related

Determine if block has already been registered

In gutenberg/block-editor, how can I check whether I've already registered a block type? Is there a function I can use? Searching through the Block Editor Handbook I couldn't see a function to check this.
An example of what I am trying to do is below:
class My_Block {
public function __construct() {
if ( ! SOME_FUNCTION_block_exists('foo/column') ) {
register_block_type( 'foo/column', my_args );
}
}
}
In WordPress Gutenberg, using JavaScript you can check if a block exists by name with getBlockType(), eg:
JavaScript
import { getBlockType } from '#wordpress/blocks';
import { registerBlockType } from '#wordpress/blocks';
if (!getBlockType('foo/column')) {
registerBlockType('foo/column', {
edit: Edit,
save,
});
}
While the above is probably the prefered way, there is a valid case for checking in PHP if a block is already registered, eg. if you want to add a render callback for a block with server side rendering. While I haven't seen a core function for this, I've found a way it can be done by using the REST API endpoint for block-types to search for the block by namespace/name:
PHP
class My_Block
{
public function __construct()
{
if (! is_block_registered('foo/column')) {
register_block_type('foo/column', $args);
}
}
private function is_block_registered($block_name)
{
// Use REST API to query if block exists by <namespace>/<name>
$route = new WP_REST_Request('GET', '/wp/v2/block-types/' . $block_name);
$request = rest_do_request($route);
if ($request->status == 404) {
// Block is not found/registered
return false;
}
// Block is registered (status is 200)
return true;
}
}
There is the method ´is_registered()´ in the class ´WP_Block_Type_Registry´ (that class handles the registration of blocks). See the docs: https://developer.wordpress.org/reference/classes/wp_block_type_registry/is_registered/
class My_Block {
public function __construct() {
if ( ! WP_Block_Type_Registry::get_instance()->is_registered( 'foo/column' ) ) {
register_block_type( 'foo/column', my_args );
}
}
}

How to Save Multiple User Metadata in Database?

I am trying to create a registration form (here) with the help of a free plugin.
There are many elements in the registration form.
In the admin panel, meta keys can be assigned for each element in the plugin interface. So there is such an opportunity.
I'm trying to collect many of the elements on the same meta key by taking advantage of this possibility. In this direction, I gave the common meta key value to the elements I created. For example: info_about_register
So far everything is fine. However, if the form is posted, I can only get the last entry in the usermeta table. So the plugin is not serializing the same meta key data. An array does not occur.
There are many form elements. I want to pull these to the admin panel later. Therefore, I think that defining a separate line for each element will tire the system a lot. I contacted the plugin developers about this issue. However, no response for about 1.5 weeks.
I tried to solve this problem myself and found the codes where the action was taken. I made some changes to these. However, I was not successful. I would be very happy if you guide me.
.../includes/class-frontend.php
/*
* Called after submission save
* Registers new user into WordPress.
* Also map field values to user meta (If configured)
*/
public function after_submission_insertion($errors, $submission, $data) {
$sub_model = erforms()->submission;
$form_model = erforms()->form;
$form = $form_model->get_form($submission['form_id']);
// Copy attachment values in data from submission (as $data does not have any uploaded file values)
if(!empty($submission['attachments'])){
foreach($submission['attachments'] as $attachment){
if(!isset($data[$attachment['f_name']])){
$data[$attachment['f_name']]= $attachment['f_val'];
}
}
}
if ($form['type'] == "reg") { // Handling of registration forms
$user = 0;
$id = 0;
// Get mapping for user meta fields if any
$user_field_map = erforms_filter_user_fields($form['id'], $submission['fields_data']);
// Avoid user registration process if user already logged in
if (!is_user_logged_in()) {
$email_or_username = $user_field_map['user_email'];
if (isset($user_field_map['password'])) {
// Silently creates user
$username = isset($user_field_map['username']) ? $data[$user_field_map['username']] : $data[$email_or_username];
do_action('erf_before_user_creation',$submission);
$id = wp_create_user($username, $data[$user_field_map['password']], $data[$email_or_username]);
} else {
// Register user and sends random password via email notification
do_action('erf_before_user_creation',$submission);
$id = register_new_user($data[$email_or_username], $data[$email_or_username]);
}
if (is_wp_error($id)) {
// In case something goes wrong delete the submission
wp_delete_post($submission['id'], true);
$error_code = $id->get_error_code();
if ($error_code == 'existing_user_login') {
$email_or_username = 'username_error';
}
$errors[] = array($email_or_username, $id->get_error_message($id->get_error_code()));
return $errors;
} else {
$selected_role = erforms_get_selected_role($submission['form_id'], $data);
if (!empty($selected_role)) { // Means user has selected any role
$user_model = erforms()->user;
$selected_role= apply_filters('erf_before_setting_user_role',$selected_role,$id,$form, $submission);
$user_model->set_user_role($id, $selected_role);
}
foreach ($user_field_map as $req_key => $meta_key) {
$is_primary_key = in_array($meta_key, erforms_primary_field_types());
if (isset($data[$req_key]) && !$is_primary_key) {
$m_keys= explode(',',$meta_key);
foreach($m_keys as $m_key){
if(!empty($m_key)){
$status = erforms_update_user_meta($id, $m_key, $data[$req_key]);
do_action('erf_user_meta_updated',$m_key,$id,$data[$req_key],$status);
}
}
}
}
do_action('erf_user_created', $id, $form['id'], $submission['id']);
}
} else {
// Get user details
$user = wp_get_current_user();
$id = $user->ID;
foreach ($user_field_map as $req_key => $meta_key) {
$is_primary_key = in_array($meta_key, erforms_primary_field_types());
if (isset($data[$req_key]) && !$is_primary_key) {
$m_keys= explode(',',$meta_key);
foreach($m_keys as $m_key){
if(!empty($m_key)){
$status= erforms_update_user_meta($id,$m_key,$data[$req_key]);
do_action('erf_user_meta_updated',$m_key,$id,$data[$req_key],$status);
}
}
}
}
//...
// User meta,URL params or default values should be prefilled only when we are not loading submission data
if(empty($submission)){
$user_meta = erforms()->user->frontend_localize_user_meta($form);
$filtered_url_params = array();
foreach ($_GET as $key => $val) {
$filtered_url_params[urldecode(strtolower(wp_unslash($key)))] = sanitize_text_field(wp_unslash($val));
}
$url_keys = array_keys($filtered_url_params);
foreach ($form['fields'] as $field) {
$label = !empty($field['label']) ? strtolower(str_replace(' ', '_', $field['label'])) : '';
$label = str_replace('&', 'and', $label); // Cause URL params do not allow &
if (!empty($field['name']) && !empty($label) && in_array($label, $url_keys)) {
if (!isset($user_meta[$field['name']]) && !empty($filtered_url_params[$label])) {
$user_meta[$field['name']] = stristr($filtered_url_params[$label], '|') ? explode('|', $filtered_url_params[$label]) : $filtered_url_params[$label];
}
}
if(!empty($field['name']) && empty($user_meta[$field['name']]) && !empty($field['value'])){
$user_meta[$field['name']] = $field['value'];
}
}
if (!empty($user_meta)) {
$data['user_meta'] = $user_meta;
}
}
$data= apply_filters('erf_form_localize_data',$data,$form);
return $data;
}
.../includes/functions.php
/**
* Wrapper to call update_user_meta function.
* This simply calls wordpress meta function and does not add any special prefix.
* Checks for any special meta key to update user table data.
* For example: display_name : updates user's display name. Instead of adding display_name usermeta
*/
function erforms_update_user_meta($user_id, $m_key, $m_val) {
switch ($m_key) {
case 'display_name' : $status = wp_update_user(array('ID' => $user_id, $m_key => $m_val));
return is_wp_error($status) ? false : true;
}
return update_user_meta($user_id, $m_key, $m_val);
}
Update:
Data can be stored as an array with a definition like below. Also, the key values ($all_meta_value[$req_key]) are equal to the id, name values automatically assigned to the HTML elements by the plugin.
Using this, different conditional states can be written.
The following code must be defined in the function.php file in the child theme:
add_action('erf_user_meta_updated','for_new_user_meta_uptated',10);
function for_new_user_meta_uptated($data){
//if the defined meta key (info_about_register) matches
if($m_key == 'info_about_register'){
$all_meta_value[$req_key] = $data;
}
}
add_action('erf_user_created', 'for_new_user_created',10);
function for_new_user_created($id){
//Save the values as a new user meta
add_user_meta($id, 'new_info_about_register', $get_meta_value);
//Remove saved single element user meta.
delete_user_meta($id, 'info_about_register');
}

How to custom title tag and meta tag description in ZF3?

I'm using Zend Framework description and I'm trying to customize title tag like ZF2 documetation recommends, but I've got this error:
Uncaught Zend\ServiceManager\Exception\ServiceNotFoundException:
Unable to resolve service "viewHelperManager" to a factory; are you
certain you provided it during configuration? in
/var/www/html/basketmetrics/vendor/zendframework/zend-servicemanager/src/ServiceManager.php:681
Stack trace: #0
/var/www/html/basketmetrics/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(757):
Zend\ServiceManager\ServiceManager->getFactory('viewHelperManag...')
1 /var/www/html/basketmetrics/vendor/zendframework/zend-servicemanager/src/ServiceManager.php(200):
Zend\ServiceManager\ServiceManager->doCreate('viewHelperManag...') #2
/var/www/html/basketmetrics/module/Stats/src/Module.php(43):
Zend\ServiceManager\ServiceManager->get('viewHelperManag...') #3
/var/www/html/basketmetrics/vendor/zendframework/zend-eventmanager/src/EventManager.php(322):
Stats\Module->setLayoutTitle(Object(Zend\Mvc\MvcEvent)) #4
/var/www/html/basketmetrics/vendor/zendframework/zend-eventmanager/src/EventManager.php(171):
Zend\EventManager\E in
/var/www/html/basketmetrics/vendor/zendframework/zend-servicemanager/src/ServiceManager.php
on line 681
This is my code on Module.php
namespace Stats;
class Module
{
const VERSION = '3.0.2';
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
/**
* #param \Zend\Mvc\MvcEvent $e The MvcEvent instance
* #return void
*/
public function onBootstrap($e)
{
// Register a render event
$app = $e->getParam('application');
$app->getEventManager()->attach('render', array($this, 'setLayoutTitle'));
}
/**
* #param \Zend\Mvc\MvcEvent $e The MvcEvent instance
* #return void
*/
public function setLayoutTitle($e)
{
$matches = $e->getRouteMatch();
$action = $matches->getParam('action');
$controller = $matches->getParam('controller');
$module = __NAMESPACE__;
$siteName = 'BasketMetrics';
// Getting the view helper manager from the application service manager
$viewHelperManager = $e->getApplication()->getServiceManager()->get('viewHelperManager');
// Getting the headTitle helper from the view helper manager
$headTitleHelper = $viewHelperManager->get('headTitle');
// Setting a separator string for segments
$headTitleHelper->setSeparator(' - ');
// Setting the action, controller, module and site name as title segments
$headTitleHelper->append($action);
$headTitleHelper->append($controller);
$headTitleHelper->append($module);
$headTitleHelper->append($siteName);
}
}
I don't know If I'm doing something wrong, or if I cannot do it like in ZF2.
And meta tag "description" how can I customize it?
->get('ViewHelperManager')
Up case

swiftmail symfony duplicate check for error log / email before sending

I would like to run a duplicate content check just before firing off an email whcih uses swiftmailer inside my symph2 app to send me dev ERROR log entries.
this functionality sits right next to my error log to database function, where it too has a duplicate check, although that one is much easier, it uses sql.
for this one, i want to maintain the last mail sent body for atleast the next 10 emails sent, so that if my error log goes out of control, it wont keep firing me duplicate emails of the same error.
should i just collect this body onto an object that holds last 10 email bodies, and attach this to the swift mailer class? or is there an easier way, like using something that is already embedded in swift mailer for this kind of post sending use? Or maybe a session..
Edit, i call swift mailer from a backend helper class, so think i can pretty much do anything there so long as its atleast semi-elegant.
EDIT this is a refined version of the method that calls both the persist and firing of email
<?php
class someWierdClass
{
public function addLogAction(Request $request, $persist = TRUE, $addEmail = TRUE)
{
$responseAdd = array();
if ($this->getRequest()->request->all() !== null) {
$data = $this->getRequest()->request->get('data') ? $this->getRequest()->request->get('data') : 'no_data';
$duplicate = $this->getRequest()->request->get('duplicate', null);
}
if ($addEmail) {
$responseAdd[] = 'firedIt';
$this->fireEmailString('You have an error log here. <br>' . $data);
}
if ($persist)
{
$responseAdd[] = 'persistedIt';
$this->persistLog($data, $duplicate);
}
if ($responseAdd)
{
$body = implode(', ', $responseAdd);
return new Response($body);
}
}
}
Log emails in a table and check that there it isn't a duplicate every time you send an email.
To do this, you should create a helper function that queries the emails table for entries who's body matches the body you would like to send. If the query returns nothing, then you know that isn't a duplicate. You would then send the email and log it the database. Otherwise, if it returned (a) record(s), you would send a dev ERROR log entry.
If you would like to only check against the last 10 emails, you would do this by querying for both $body == $new_body and $id >= ($total_rows-10)
You would then inject this into the container and call it using something like this
$this->container->get('helper')->sendEmail($body, $subject, $recipients);
Ok, thanks Dan for the idea as to using the database to do the dup check. If you notice, per your suggestion, i was already doing the dup check, but it made me think. It helped me connect the dots.
What i have done is return the answer if its a duplicate on the response when it does the updating the database, then using that response as a flag to determine if email fires or not. (in my case, i go further to check the updated stamp is at least +1 hour old, as opposed to the 'last 10 emails content' idea)
Heres the code.. Enjoy..
<?php
namespace Acme\AcmeBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller,
Acme\AcmeBundle\Entity\Log,
Symfony\Component\HttpFoundation\JsonResponse,
Symfony\Component\HttpFoundation\Response,
Symfony\Component\Config\Definition\Exception\Exception,
Symfony\Component\HttpFoundation\Request,
Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
class someWierdClass
{
/**
* #var array
*/
protected $senderArray = array('no-reply#yorudomain.com' => 'Your Website Name');
/**
* #param Request $request
* #param bool $persist
* #param bool $addEmail
* #return Response
*/
public function addLogAction(Request $request, $persist = TRUE, $addEmail = TRUE)
{
$responseAdd = array();
if ($this->getRequest()->request->all() !== null) {
$data = $this->getRequest()->request->get('data') ? $this->getRequest()->request->get('data') : 'no_data';
$type = $this->getRequest()->request->get('type') ? $this->getRequest()->request->get('type') : 'no_type';
$duplicate = $this->getRequest()->request->get('duplicate', null);
}
if ($addEmail) {
$responseAdd[] = 'firedIt';
$this->fireEmailString('You have an error log here. <br>' . $data);
}
if ($persist) {
$responseAdd[] = 'persistedIt';
$persistResponse = $this->persistLog( $type = $data, $duplicate);
if ($persistResponse) {
// a dup check is done here and results of this is on the response. (e.g. $content->passesCutoff)
$content = json_decode($persistResponse->getContent());
}
}
if ( $addEmail && ( isset($content->passesCutoff) && $content->passesCutoff ))
{
//fire off an email also, because its kind of hard to look in teh logs all the time, sometimes we just want an email.
$successEmail = $this->fireEmailString($data);
if( ! $successEmail )
{
$responseAdd[] = 'firedIt';
}
}
if ($responseAdd) {
$body = implode(', ', $responseAdd);
return new Response($body);
}
}
/**
* #param $emailStringData
* #param null $emailSubject
* #param null $emailTo
* #return mixed
*/
protected function fireEmailString($emailStringData, $emailSubject = null, $emailTo=null){
$templateName = 'AcmeBundle:Default:fireEmailString.html.twig';
if( ! $emailSubject )
{
$emailSubject = 'An email is being fired to you!' ;
}
if( ! $emailTo )
{
$emailTo = 'youremail#gmail.com';
}
$renderedView = $this->renderView(
$templateName, array(
'body' => $emailStringData,
));
$mailer = $this->get('mailer');
$message = $mailer->createMessage()
->setSubject( $emailSubject)
->setBody($emailStringData, 'text/plain')
->addPart($renderedView, 'text/html')
->setFrom($this->senderArray)
->setSender($this->senderArray)
->setTo($emailTo);
$results = $mailer->send($message);
return $results;
}
/**
* #param $type
* #param $data
* #param $duplicate
* #return JsonResponse
*/
protected function persistLog($type, $data, $duplicate) {
$em = $this->getDoctrine()->getManager();
$count = null;
$passesCutoff = null;
$mysqlNow = new \DateTime(date('Y-m-d G:i:s'));
//only two conditions can satisy here, strings '1' and 'true'.
if($duplicate !== '1' && $duplicate !== 'true' /*&& $duplicate != TRUE*/)
{
//in order to check if its unique we need to get the repo
//returns an object (findByData() would return an array)
$existingLog = $em->getRepository('AcmeBundle:Log')->findOneByData(
array('type' => $type, 'data' => $data)
);
if($existingLog)
{
$timeUpdatedString = strtotime($existingLog->getTimeupdated()->format('Y-m-d H:i:s'));
$cutoffStamp = strtotime('+1 hour', $timeUpdatedString); //advance 1 hour (customize this to the amount of time you want to go by before you consider this a duplicate. i think 1 hour is good)
$passesCutoff = time() >= $cutoffStamp ? TRUE : FALSE; //1 hour later
$count = $existingLog->getUpdatedcount();
$existingLog->setUpdatedcount($count + 1); // '2014-10-11 03:52:20' // date('Y-m-d G:i:s')
$em->persist($existingLog);
}
else
{
//this record isnt found, must be unique
$newLog = new Log(); //load our entity
//set in new values
$newLog->setType($type);
$newLog->setData($data);
$newLog->setUpdatedcount(0);
$newLog->setTimeupdated($mysqlNow);
$em->persist($newLog);
}
}
else
{
//we dont care if unique or not, we just want a new row
$newLog = new Log(); //load our entity
$newLog->setType($type);
$newLog->setData($data);
//time updated has been set to auto update to current timestamp in the schema, test first, then remove this
$newLog->setUpdatedcount(0);
$newLog->setTimeupdated($mysqlNow);
$em->persist($newLog);
}
$em->flush();
$response = new JsonResponse();
$response->setData(
array(
'data' => 'persistedIt',
'existingLog' => $count,
'passesCutoff' => $passesCutoff,
));
return $response;
}
}
In hindsight, i would have just passed the last update timestamp back on the response from the persist method, then do the cutoff calculation inside the fire email method obviously, but the above code does work as a starting point.. :-)

How to make instant redirection in Laravel

I want to make an instant redirection in my controller in Laravel.
I know I can use
public function show($page)
{
return Redirect::url('http://example.com');
}
but I want to repeat this code in many controllers adding condition for example I would like to do something like this:
public function show($page)
{
$totalPages = 100; // here calculating maximum page
if ($page < 2 || $page > $totalPages) {
return Redirect::url('http://example.com');
}
// rest of code here - should be run if condition is false
}
but I don't want to repeat code in each controller.
If I try put redirection code in other method (that could exist in base controller) it won't work because it doesn't return anything in main controller:
public function show($page)
{
$totalPages = 100; // here calculating maximum page
$this->checkPages($page, $totalPages, 'http://example.com');
// rest of code here - should be run if condition is false
}
public function checkPages($page, $totalPages, $url)
{
if ($page < 2 || $page > $totalPages) {
return Redirect::url($url);
}
}
How can I solve this issue?
After a while of digging it seems that for this purposes you should use send() method from Symfony\Component\HttpFoundation (Laravel RedirectResponse inherits from this class).
So you can modify checkPages method this way:
public function checkPages($page, $totalPages, $url)
{
if ($page < 2 or $page > $totalPages) {
Redirect::url($url)->send();
}
}
and it will make instant redirection.
You have to return the results of the method in the base controller.
return $this->checkPages($page, $totalPages, 'http://example.com');
I'd probably suggest that your checkPages method is trying to do too much. Would I expect checkPages (which maybe should be validatePageNumber() or similar) to return a redirect? No, I'd expect it to return true or false.
That gives you this as your logic:
/**
* Make sure the current page is between 1 and $lastPage
*
* #param int $page
* #param int $lastPage
* #return bool
*/
protected function validatePageNumber( $page, $lastPage ) {
return $page < 2 || $page > $lastPage;
}
and now your controller logic is trivial:
public function show( $page ) {
$totalPages = 100;
if ( ! $this->validatePageNumber( $page, $totalPages ) ) {
return Redirect::url( 'http://example.com' );
}
// rest of code here - should be run if condition is false
}
Now if we use quasi-English to read your code, you have a public method show($page) which shows a page: it sets the total number of pages, checks that $page is valid, and if not, redirects somewhere. All of this is control logic, and only control logic, which is what a controller should be doing.
Your validatePageNumber() can now be abstracted into a model, or better yet, a ServiceProvider, and it does one job: validates that a number is between 1 and n.

Resources