How to create PDF file using Wordpress Rest API - wordpress

I am trying to create a PDF file using WP Rest API. I wrote this small code on function.php. But when I call the API from the postman, it shows - Internal Server Error.
Here is my code:
add_action(
'rest_api_init',
function () {
register_rest_route(
'api',
'/get_location',
array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'get_location',
)
);
}
);
function get_location() {
global $wpdb;
$results = array();
require get_stylesheet_directory() . '/dompdf/autoload.inc.php';
use Dompdf\Dompdf;
use Dompdf\Options;
$options = new Options();
$options->set( 'isRemoteEnabled', true );
// Instantiate and use the dompdf class
$dompdf = new Dompdf( $options );
$dompdf->loadHtml( 'hello world<br/>TEST' );
$dompdf->setPaper( 'A4', 'landscape' );
// Render the HTML as PDF
$dompdf->render();
$output = $dompdf->output();
$now = strtotime( 'now' );
// file_put_contents($now.".pdf", $output);
file_put_contents( get_stylesheet_directory() . '/dompdf/' . $now . '.pdf', $output );
return $results;
The above code show internal server error in postman

Related

Add different WordPress excerpt formats to different templates

I added the following code to my functions.php file in WordPress 6.1.1 to display excerpts.
function new_excerpt_length($length) {
return 100;
}
add_filter('excerpt_length', 'new_excerpt_length');
function new_excerpt_more($more) {
return '...';
}
add_filter('excerpt_more', 'new_excerpt_more');
...but I also have a use case to show the full excerpt without a read more link.
On page template 1 I add the below code to display the excerpt:
<?php echo the_excerpt(); ?>
...and it displays the excerpt as per the functions.php file but how do I create a 2nd excerpt without the read more link and apply it to page template 2?
Is there a parameter I can use within the_excerpt(parameter); or can I use something like wp_trim_excerpt https://developer.wordpress.org/reference/functions/wp_trim_excerpt/ maybe?
I came across the below code that is supposed to do what I want
function wpex_get_excerpt( $args = array() ) {
// Default arguments.
$defaults = array(
'post' => '',
'length' => 40,
'readmore' => false,
'readmore_text' => esc_html__( 'read more', 'text-domain' ),
'readmore_after' => '',
'custom_excerpts' => true,
'disable_more' => false,
);
// Apply filters to allow child themes mods.
$args = apply_filters( 'wpex_excerpt_defaults', $defaults );
// Parse arguments, takes the function arguments and combines them with the defaults.
$args = wp_parse_args( $args, $defaults );
// Apply filters to allow child themes mods.
$args = apply_filters( 'wpex_excerpt_args', $args );
// Extract arguments to make it easier to use below.
extract( $args );
// Get the current post.
$post = get_post( $post );
// Get the current post id.
$post_id = $post->ID;
// Check for custom excerpts.
if ( $custom_excerpts && has_excerpt( $post_id ) ) {
$output = $post->post_excerpt;
}
// No custom excerpt...so lets generate one.
else {
// Create the readmore link.
$readmore_link = '' . $readmore_text . $readmore_after . '';
// Check for more tag and return content if it exists.
if ( ! $disable_more && strpos( $post->post_content, '<!--more-->' ) ) {
$output = apply_filters( 'the_content', get_the_content( $readmore_text . $readmore_after ) );
}
// No more tag defined so generate excerpt using wp_trim_words.
else {
// Generate an excerpt from the post content.
$output = wp_trim_words( strip_shortcodes( $post->post_content ), $length );
// Add the readmore text to the excerpt if enabled.
if ( $readmore ) {
$output .= apply_filters( 'wpex_readmore_link', $readmore_link );
}
}
}
// Apply filters and return the excerpt.
return apply_filters( 'wpex_excerpt', $output );
}
Output using:
<?php echo wpex_get_excerpt ( $defaults = array(
'length' => 40,
'readmore' => true,
'readmore_text' => esc_html__( 'read more', 'wpex-boutique' ),
'custom_excerpts' => true,
) ); ?>
...but doesn't seem to workas intended. Outputs the excerpt with no link but the args don't see to work when changed. Would be perfect for my use otherwise. Maybe someone sees how to fix this code?
Thanks

save_post function is not called

I am trying to call the save_post or publish_post hook with my function it the function cannot be triggered.
My function works well on single.php but it only assigns thumbnails after browsing the post. So I decided to put it inside functions.php but I could not get it triggered with save_post or publish_post hooks.
Here is the code
function catch_that_image($post_id) {
if(is_single()){
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "https://images.arabicpdfs.com/المكتبة-المفتوحة.jpg";
}
//return $first_img;
if ( has_post_thumbnail() ) {
return;
}
else{
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
$url =$first_img;
$desc = "image description";
$post_id =$post->ID;
$image = media_sideload_image( $url, $post_id, $desc,'id' );
set_post_thumbnail( $post_id, $image );
//echo $post_id;
}
}}
add_action( 'publish_post', 'catch_that_image', 10, 1);
I could not figure out what I am missing
The function is_single does not work in this hook (even with post id as parameter). According to documentation the hook publish_post already specifies that it is a post see here and therefore the if-statement is not necessary. The suffix _post defines the post type for which the hook is valid.
I would also pass the post as a parameter.
function catch_that_image($post_id, $post)
{
...
}
add_action('publish_post', 'catch_that_image', 10, 2);
As an alternative I would recommend the transition_post_status hook see here
I would recommend you the hook transition_post_status
function custom_transition_post_status($new_status, $old_status, $post)
{
// here you can do your action something like this
if(is_single() && $post->post_type == 'post') {
...
}
}
add_action('transition_post_status', 'custom_transition_post_status', 10, 3);
The insert or update should be done with the function wp_insert_post. Add the field ID if you want do update your post.
$postData = [
'post_title' => 'your title',
'post_status' => 'publish',
'post_type' => 'post'
];
$postId = wp_insert_post($postData);

Woocommerce ajax call on single product page

I get all my products from an API and those who are variations to each other all share a custom meta key called "api_product_family". The products with the same api_product_family are variants to each other, so on the single page I have a hook where I display the other variants with image and anchor to it's variants.
My code:
function mv_variations() {
global $post;
global $wpdb;
$product_id = $post->ID;
$product_family = get_post_meta( $post->ID, 'api_product_family', true );
if(!empty($product_family)) {
$query = "
SELECT post_id
FROM " . $wpdb->prefix . "postmeta
WHERE meta_value = '" . $product_family . "'
";
$products = $wpdb->get_col($query);
if(count($products) > 0) {
for($i=0; $i<count($products); $i++) {
if($products[$i] == $product_id) {
unset($products[$i]);
}
}
if(count($products) > 0) {
print '<h3>Choose other variants: </h3>';
foreach($products as $product) {
$image = wp_get_attachment_image_src(get_post_thumbnail_id($product));
print '<img src="' . $image[0] . '" alt="img"/> ';
}
}
}
}
}
add_action( 'woocommerce_single_product_summary', 'mv_variations' );
The problem:
I have a LOT of posts, and a lot of post_meta's, so it's taking an eternity to load so I was thinking to move this whole function inside and AJAX call so it's doesn't slow down the initial load. The problem is that I have no idea how to do that with wordpress
Are you simply looking to run a WP function via AJAX?
1) Add ajax actions
This needs to run inside the main plugin file. If you run this only on the public code, it will not work. WP is a little weird and all ajax uses admin-ajax.php
if ( wp_doing_ajax() ){
add_action( 'wp_ajax_yourcustomfunction', array($this, 'yourcustomfunction') );
add_action( 'wp_ajax_nopriv_yourcustomfunction', array($this, 'yourcustomfunction') );
}
function yourcustomfunction(){
echo 'success';
exit();
}
2) In JavaScript
in the backend, you have the global: ajaxurl for the ajax url
BUT in the front end you need to pass this as a variable via wp_localize_script
$datatoBePassed = array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
);
wp_localize_script( 'your_javascript_script', 'plugin_display_settings', $datatoBePassed );
In JS:
var datavar = {
action: 'yourcustomfunction',
};
$.post(plugin_display_settings.ajaxurl, datavar, function(response){
//response received here. It will be 'success' which is echoed in PHP
});
3)
If you also want to run a security nonce check (to check the request truly originates from the WP website, prevents some attacks), it gets a little more complicated:
$datatoBePassed should also include 'security' => wp_create_nonce( 'yourplugin_security_nonce' ),
datavar in JS includes security: plugin_display_settings.security,
Finally, your PHP custom function begins with:
// Check security nonce.
if ( ! check_ajax_referer( 'yourplugin_security_nonce', 'security' ) ) {
wp_send_json_error( 'Invalid security token sent.' );
wp_die();
}
// If security check passed, run further
So I think you might get better performance using WP_Query. Below I converted what you have into a custom WP_Query. May need some slight adjustment but should be the right direction.
function mv_variations() {
global $post_id;
// get current post "product family"
$product_family = get_post_meta( $post_id, 'api_product_family', true );
// build related "product family" products query
$products_query_args = array(
'post_type' => 'product', // may need to update this for your case
'posts_per_page' => -1, // return all found
'post__not_in' => array($post_id), // exclude current post
'post_status' => 'publish',
// use a meta query to pull only posts with same "product family" as current post
'meta_query' => array(
array(
'key' => 'api_product_family',
'value' => $product_family,
'compare' => '='
)
)
);
$products_query = new WP_Query($products_query);
// use "the loop" to display your products
if ( $products_query->have_posts() ) :
print '<h3>Choose other variants: </h3>';
while ( $products_query->have_posts() ) : $products_query->the_post();
print ''. wp_get_attachment_image() .'';
endwhile;
// restore global post
wp_reset_postdata();
endif;
}
add_action( 'woocommerce_single_product_summary', 'mv_variations' );

Inserting checkbox values into WordPress database

I am trying to insert the values of all ticked checkboxes in a wordpress database, into a table which i created myself. Here's my jQuery code:
$(document).ready(function(){
$('#submit').click(function(){
var insert = [];
$('.get_value').each(function(){
if($(this).is(":checked") ){
insert.push($(this).val() );
}
});
insert = insert.toString();
$.ajax({
url:"insert.php",
method:"POST",
data:{insert:insert},
success:function(data){
$('.result').html(data);
}
});
});
});
and my insert code, (its in insert.php):
if ( isset($_POST["insert"]) ){
global $wpdb;
$table_name = $wpdb->prefix . "status";
$wpdb->insert($table_name, array(
'status' => 'approved'
);
}
its not showing any errors, but its not inserting either.I dont know if this information is useful, but the checkboxes are at the admin backend as part of a custom post type.
This isn't going to work, because you are calling insert.php in your ajax call. The url should point to ajaxurl that is localized with the script where your ajax is.
So if your script is located in file called custom.js and you have it enqueued it like:
wp_enqueue_script( 'my_custom_script', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ),'', true );
Then you'll localize your ajax url like
wp_localize_script( 'my_custom_script', 'ajax_call', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
) );
And use it in your script like
$(document).ready(function(){
$('#submit').click(function(){
var insert = [];
$('.get_value').each(function(){
if($(this).is(":checked") ){
insert.push($(this).val() );
}
});
insert = insert.toString();
$.ajax({
url: ajax_call.ajaxurl,
method:"POST",
data:{
'action': 'my_action_callback',
'insert': insert,
},
success:function(data){
$('.result').html(data);
}
});
});
});
Also your insert.php code should be inside a function hooked on wp_ajax hooks
add_action( 'wp_ajax_my_action_callback', 'my_action_callback' );
add_action( 'wp_ajax_nopriv_my_action_callback', 'my_action_callback' );
function my_action_callback(){
if ( isset($_POST["insert"]) ){
global $wpdb;
$table_name = $wpdb->prefix . "status";
$wpdb->insert($table_name, array(
'status' => 'approved'
);
}
}
https://codex.wordpress.org/AJAX_in_Plugins

adding custom page template from plugin

I'm working on building my first plugin for wordpress and am needing it to dynamically add a custom page for a login screen among other things.
The only thing I've been able to find that's anywhere near what I'm needing is here: WP - Use file in plugin directory as custom Page Template? & Possible to add Custom Template Page in a WP plugin?, but they're still not quite what I'm looking for.
Here is the code that I currently have running in my plugin...
// Add callback to admin menu
add_action( 'template_redirect', 'uploadr_redirect' );
// Callback to add menu items
function uploadr_redirect() {
global $wp;
$plugindir = dirname( __FILE__ );
// A Specific Custom Post Type
if ( $wp->query_vars["post_type"] == 'uploadr' ) {
$templatefilename = 'custom-uploadr.php';
if ( file_exists( TEMPLATEPATH . '/' . $templatefilename )) {
$return_template = TEMPLATEPATH . '/' . $templatefilename;
} else {
$return_template = $plugindir . '/themefiles/' . $templatefilename;
}
do_theme_redirect( $return_template );
}
}
function do_theme_redirect( $url ) {
global $post, $wp_query;
if ( have_posts ()) {
include( $url );
die();
} else {
$wp_query->is_404 = true;
}
}
Using this would require that my client create new page... what I'm needing is for the pluging to auto create a custom page (with a customized path, meaning .com/custompathhere) using a template file from the plugin folder, which will then contain all actions the plugin performs.
Note: This plugin is designed to run on one page, therefore reducing load-time and etc.
Thanks in advance!
Here is my code solution for adding page templates from a Wordpress plugin (inspired by Tom McFarlin).
This is designed for a plugin (the template files are searched for in the root directory of the plugin). These files are also in exactly the same format as if they were to be included directly in a theme. This can be changed if desired - check out my full tutorial http://www.wpexplorer.com/wordpress-page-templates-plugin/ for greater detail on this solution.
To customise, simply edit the following code block within the __construct method;
$this->templates = array(
'goodtobebad-template.php' => 'It\'s Good to Be Bad',
);
Full code;
class PageTemplater {
/**
* A Unique Identifier
*/
protected $plugin_slug;
/**
* A reference to an instance of this class.
*/
private static $instance;
/**
* The array of templates that this plugin tracks.
*/
protected $templates;
/**
* Returns an instance of this class.
*/
public static function get_instance() {
if( null == self::$instance ) {
self::$instance = new PageTemplater();
}
return self::$instance;
}
/**
* Initializes the plugin by setting filters and administration functions.
*/
private function __construct() {
$this->templates = array();
// Add a filter to the attributes metabox to inject template into the cache.
add_filter(
'page_attributes_dropdown_pages_args',
array( $this, 'register_project_templates' )
);
// Add a filter to the save post to inject out template into the page cache
add_filter(
'wp_insert_post_data',
array( $this, 'register_project_templates' )
);
// Add a filter to the template include to determine if the page has our
// template assigned and return it's path
add_filter(
'template_include',
array( $this, 'view_project_template')
);
// Add your templates to this array.
$this->templates = array(
'goodtobebad-template.php' => 'It\'s Good to Be Bad',
);
}
/**
* Adds our template to the pages cache in order to trick WordPress
* into thinking the template file exists where it doens't really exist.
*
*/
public function register_project_templates( $atts ) {
// Create the key used for the themes cache
$cache_key = 'page_templates-' . md5( get_theme_root() . '/' . get_stylesheet() );
// Retrieve the cache list.
// If it doesn't exist, or it's empty prepare an array
$templates = wp_get_theme()->get_page_templates();
if ( empty( $templates ) ) {
$templates = array();
}
// New cache, therefore remove the old one
wp_cache_delete( $cache_key , 'themes');
// Now add our template to the list of templates by merging our templates
// with the existing templates array from the cache.
$templates = array_merge( $templates, $this->templates );
// Add the modified cache to allow WordPress to pick it up for listing
// available templates
wp_cache_add( $cache_key, $templates, 'themes', 1800 );
return $atts;
}
/**
* Checks if the template is assigned to the page
*/
public function view_project_template( $template ) {
global $post;
if (!isset($this->templates[get_post_meta(
$post->ID, '_wp_page_template', true
)] ) ) {
return $template;
}
$file = plugin_dir_path(__FILE__). get_post_meta(
$post->ID, '_wp_page_template', true
);
// Just to be safe, we check if the file exist first
if( file_exists( $file ) ) {
return $file;
}
else { echo $file; }
return $template;
}
}
add_action( 'plugins_loaded', array( 'PageTemplater', 'get_instance' ) );
Check out my tutorial on this for more info.
http://www.wpexplorer.com/wordpress-page-templates-plugin/
I hope this helps you in what you want to do :)
I actually was able to talk to a developer friend of mine after revising the code quite a bit.
Here it is...
<?php
register_activation_hook( __FILE__, 'create_uploadr_page' );
function create_uploadr_page() {
$post_id = -1;
// Setup custom vars
$author_id = 1;
$slug = 'event-photo-uploader';
$title = 'Event Photo Uploader';
// Check if page exists, if not create it
if ( null == get_page_by_title( $title )) {
$uploader_page = array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => $author_id,
'post_name' => $slug,
'post_title' => $title,
'post_status' => 'publish',
'post_type' => 'page'
);
$post_id = wp_insert_post( $uploader_page );
if ( !$post_id ) {
wp_die( 'Error creating template page' );
} else {
update_post_meta( $post_id, '_wp_page_template', 'custom-uploadr.php' );
}
} // end check if
}
add_action( 'template_include', 'uploadr_redirect' );
function uploadr_redirect( $template ) {
$plugindir = dirname( __FILE__ );
if ( is_page_template( 'custom-uploadr.php' )) {
$template = $plugindir . '/templates/custom-uploadr.php';
}
return $template;
}
?>
I'm providing a general solution for those that want to add a template to a post from the their plugin. Use the single_template filter.
<?php
add_filter( 'single_template', 'add_custom_single_template', 99 );
function add_custom_single_template( $template ) {
return plugin_dir_path( __FILE__ ) . 'path-to-page-template-inside-plugin.php';
}
?>
Also, if you want to use the template in a specific post type, then:
<?php
add_filter( 'single_template', 'add_custom_single_template', 99 );
function add_custom_single_template( $template ) {
if ( get_post_type() == 'post-type-name'; ) {
return plugin_dir_path( __FILE__ ) . 'path-to-page-template-inside-plugin.php';
}
return $template;
}
?>

Resources