Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

PHP creates JS and CSS File for Frontend. Need to include files with $post_id and add_action('wp_enqueue_scripts','load_front_scripts'); WordPress

  • SOLVED

My PHP Script creates a javascript and css file in upload directory width the wordpress filesystem with the post_id at the end of the filename when i save the metabox.
In my Scripts.php the files should be imported as script and css, but i need to transfer the post_id from the metabox to get the correct filename. How can i do this?
get_the_ID() is not working correct, because it shows only the id of the current page not of the post id from my metabox...

Here my Metabox-Save Function

add_action('save_post','arti_carousel_save'); //Save Code
function arti_carousel_save( $post_id )
{
//Security
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
};
//Nonce-Field Check
if ( ! isset($_POST['arti_carousel_meta_box_nonce'])){
return;
}
if( ! wp_verify_nonce($_POST['arti_carousel_meta_box_nonce'], 'arti_carousel_save_meta_box_data')){
return;
}
//Nonce-Field Check END
if ( 'arti_carousel' == $_POST['post_type']){
if( !current_user_can( 'edit_page', $post_id) || !current_user_can( 'edit_post', $post_id)){
return;
};
};
//Security END
$titles = (array) $_POST['carousel_title'];
$images = (array) $_POST['carousel_image'];
$contents = (array) $_POST['carousel_content'];
$_arti_carousels = array();
foreach($titles as $key=>$val) {
$_arti_carousels[] = array(
'title' => sanitize_text_field($titles[$key]),
'image' => intval($images[$key]),
'content' => sanitize_textarea_field($contents[$key]),
);
};

include('metabox-save/fields-basic-setings.php');
include('metabox-save/fields-formattings.php');

//Load CSS Code for File
include('metabox-save/getCSS.php');
//Load JavaScript Code for File
include('metabox-save/getJavaScript.php');

cssfile($post_id,$cssFile); //The functions to create the CSSFile
jsfile($post_id,$jsFile); //The functions to create the JsFile

update_post_meta($post_id, '_arti_carousels_editor', ($_arti_carousels));
}



Here the functions to create the Files, both working correct
function cssfile($id,$cssFile)
{
$post_id = get_the_ID();
require_once( ABSPATH . 'wp-admin/includes/file.php' ); // you have to load this file
global $wp_filesystem;
$upload_dir = wp_upload_dir();
WP_Filesystem(); // Initial WP file system
$dirCSS = trailingslashit($upload_dir['basedir']) . 'arti-carousel/';
$cssCode = $cssFile;
$wp_filesystem->mkdir($dirCSS); // Make a new directory folder if folder not their
$wp_filesystem->put_contents($dirCSS . 'arti-carousel-post-' . $id . '.css', $cssCode, 0644); // Finally, store the file :D
}
function jsfile($id,$jsFile)
{
$post_id = get_the_ID();
require_once( ABSPATH . 'wp-admin/includes/file.php' ); // you have to load this file
global $wp_filesystem;
$upload_dir = wp_upload_dir();
WP_Filesystem(); // Initial WP file system
$dirCSS = trailingslashit($upload_dir['basedir']) . 'arti-carousel/';
$jsCode = $jsFile;
$wp_filesystem->mkdir($dirCSS); // Make a new directory folder if folder not their
$wp_filesystem->put_contents($dirCSS . 'arti-carousel-post-' . $id . '.js', $jsCode, 0644); // Finally, store the file :D
}


Here my Scripts PHP File to import the Script and CSS to Frontend

add_action('wp_enqueue_scripts','load_front_scripts');
function load_front_scripts($postid){
$uploads = wp_upload_dir();
$postid = get_queried_object_id();

//Include Front Dynamic Generated JavaScript ($post_id need to be imported from metabox)
wp_register_script('arti_carousel_post_front_js', trailingslashit($uploads['baseurl']) . 'arti-carousel/arti-carousel-post-'.$post_id.'.js', __FILE__);
wp_enqueue_script('arti_carousel_post_front_js');

//Include Front Dynamic Generated CSS ($post_id need to be imported from metabox)
wp_register_style('arti_carousel_post_front_css', trailingslashit($uploads['baseurl']) . 'arti-carousel/arti-carousel-post-'.$post_id.'.css', __FILE__);
wp_enqueue_style('arti_carousel_post_front_css');



/////////////////////////////////////////
It would be also possible to use an individual id for each creation of the scripts and metabox. i only need for each post element an individual css and js file that i can include after creation in frontend with these id...

Answers (4)

2019-09-22

Hariprasad Vijayan answers:

Hi there,
wp_enqueue_scripts doesn't support a variable for postid. Try following code instead.

function load_front_scripts(){
$uploads = wp_upload_dir();
global $post;
$postid = $post->ID;

global $post; will hold the current page/post object.

Best wishes,
Hariprasad


User183722 comments:

It will not work, because the global $post creates the ID of the current frontend Page / Post ID, not the ID of the Backend PostID of my custom_post_type (Metabox, that i also use as shortcode ID)...
Is it perhaps possible to include the script in my add_shortcode function?


Hariprasad Vijayan comments:

wp_enqueue_scripts fires when header and footer renders, shortcode only renders when that specific location of code executes. you can't enqueue a script from a shortcode using wp_enqueue_scripts, you need to include it from shortcode itself.


User183722 comments:

Thanks for your statement! Did you have an example how i can do it?


Hariprasad Vijayan comments:

In your case it would be something like this.
add_shortcode('arti_carousel', 'arti_carousel_display');
function arti_carousel_display($atts, $content = null)
{
$post_id = $atts['id'];
$uploads = wp_upload_dir();
$style_script = '<script src="'.trailingslashit($uploads['baseurl']) . 'arti-carousel/arti-carousel-post-'.$post_id.'.js"></script>';
$style_script .= '<link rel="stylesheet" type="text/css" href="'.trailingslashit($uploads['baseurl']) . 'arti-carousel/arti-carousel-post-'.$post_id.'.css">';
return $style_script;
}

You need to modify it slightly based on your current code that return from add_shortcode.


User183722 comments:

Ah ok, i understand. But then it the script and css are not in the header and can not compiled by seo plugins, right? Give it perhaps a possibility to put it to the header perhaps with an individual id that gernerated in the metabox?


Hariprasad Vijayan comments:

It is probably not possible to call the script in header or footer when it rendering inside a shortcode function.
Like if you have written a WP_Query inside the add_shortcode function we can't figure out the post ids that generating using the query.

If you are passing the post id as an attribute of the shortcode, we can try some script to extract the post id from the content of the post.

How the shortcode function is working?


User183722 comments:

At the Moment the Frontend get only static code in of the shortcode. I have worked the most of the time on the backend functions...

add_shortcode('arti_carousel', 'arti_carousel_display');
function arti_carousel_display($atts, $content = null)
{
$post_id = $atts['id'];

// check if published. If not, cancel
if (get_post_status($post_id) != 'publish')
return;

$output = ' ...... html code .....';
return $output;
};


User183722 comments:

In the shortcode the $post_id = $atts['id']; give the correct id 293 and not the id 13 from the frontend-page....


Hariprasad Vijayan comments:

Try this,

function enqueu_script_based_on_shortcode_parameter()
{
global $post;
$pattern = get_shortcode_regex();

if ( preg_match_all( '/'. $pattern .'/s', $post->post_content, $matches )
&& array_key_exists( 2, $matches )
&& in_array( 'arti_carousel', $matches[2] ) )
{
$params = array();
$dat= explode(" ", $matches[3][0]);
foreach ($dat as $d){
list($opt, $val) = explode("=", $d);
$params[$opt] = trim($val, '"');
}
$post_id = $params['id'];
$uploads = wp_upload_dir();
//Include Front Dynamic Generated JavaScript ($post_id need to be imported from metabox)
wp_register_script('arti_carousel_post_front_js', trailingslashit($uploads['baseurl']) . 'arti-carousel/arti-carousel-post-'.$post_id.'.js', __FILE__);
wp_enqueue_script('arti_carousel_post_front_js');

//Include Front Dynamic Generated CSS ($post_id need to be imported from metabox)
wp_register_style('arti_carousel_post_front_css', trailingslashit($uploads['baseurl']) . 'arti-carousel/arti-carousel-post-'.$post_id.'.css', __FILE__);
wp_enqueue_style('arti_carousel_post_front_css');
}
}
add_action( 'wp', 'enqueu_script_based_on_shortcode_parameter' );

The above code reads post content and extract id from shortcode to enqueue script and style.


User183722 comments:

Thanks you realy much, it works fine! Very good solution... I have only one small problem now. Jquery is loading later and the script not still work. How i can tell the script that jquery need to be load before?


Hariprasad Vijayan comments:

Try this
function enqueu_script_based_on_shortcode_parameter()
{
global $post;
$pattern = get_shortcode_regex();
$uploads = wp_upload_dir();

if (
preg_match_all('/' . $pattern . '/s', $post->post_content, $matches)
&& array_key_exists(2, $matches)
&& in_array('arti_carousel', $matches[2])
) {
foreach ($matches[3] as $match) {
$params = array();
$dat = explode(" ", $match);
foreach ($dat as $d) {
list($opt, $val) = explode("=", $d);
$params[$opt] = trim($val, '"');
}
$post_id = $params['id'];

//Include Front Dynamic Generated JavaScript ($post_id need to be imported from metabox)
wp_register_script('arti_carousel_post_front_js-'.$post_id, trailingslashit($uploads['baseurl']) . 'arti-carousel/arti-carousel-post-' . $post_id . '.js', array('jquery'));
wp_enqueue_script('arti_carousel_post_front_js-'.$post_id);

//Include Front Dynamic Generated CSS ($post_id need to be imported from metabox)
wp_register_style('arti_carousel_post_front_css-'.$post_id, trailingslashit($uploads['baseurl']) . 'arti-carousel/arti-carousel-post-' . $post_id . '.css');
wp_enqueue_style('arti_carousel_post_front_css-'.$post_id);
}
}
}
add_action('wp', 'enqueu_script_based_on_shortcode_parameter');


User183722 comments:

Thanks, it works!

2019-09-22

Fahad Murtaza answers:

global $post

is the way usually.


User183722 comments:

I have checked this already and i get the post id 13, but when i look to my shortcode or metaboxes i get the id 293... 13 is the id of the page not of the post from my plugin

2019-09-22

Shabeer M answers:

Just rewrite your enqueue script post id fetching like the following. Please let me know if you have any query

add_action('wp_enqueue_scripts','load_front_scripts');
function load_front_scripts(){
global $post; //added global var $post
$uploads = wp_upload_dir();
$postid = $post->ID; //using post id here

.......


User183722 comments:

I have checked this already and i get the post id 13, but when i look to my shortcode or metaboxes i get the id 293... 13 is the id of the page not of the post from my plugin


Shabeer M comments:

Then please load the script in init hook, move from the action wp_enqueue_scripts


Shabeer M comments:

Or please give me the login credentials of your site to 007shabeerm@ gmail.com


Shabeer M comments:

https://code.hyperspatial.com/all-code/wordpress-code/get-post-id-and-enqueue-scripts/

Please try the first option. It will fix your issue i think.
Action hook changed in this example


User183722 comments:

I think it will not work, because the global $post creates the ID of the current frontend Page / Post ID, not the ID of the Backend PostID of my custom_post_type (Metabox, that i also use as shortcode ID)...
Is it perhaps possible to include the script in my add_shortcode function?

In my Shortcode i get the ID:
add_shortcode('arti_carousel', 'arti_carousel_display');

function arti_carousel_display($atts, $content = null)
{
$post_id = $atts['id'];


User183722 comments:

Something like that:

function arti_carousel_display($atts, $content = null)
{
$post_id = $atts['id'];

function load_front_post_scripts($post_id)
{

$postid = $post_id; //using post id here
wp_register_script('arti_carousel_post_front_js', trailingslashit($uploads['baseurl']) . 'arti-carousel/arti-carousel-post-'.$postid.'.js', __FILE__);
wp_enqueue_script('arti_carousel_post_front_js');

wp_register_style('arti_carousel_post_front_css', trailingslashit($uploads['baseurl']) . 'arti-carousel/arti-carousel-post-'.$postid.'.css', __FILE__);
wp_enqueue_style('arti_carousel_post_front_css');
};

2019-09-22

Mohamed Ahmed answers:

Hello,

Could you change
$post_id = get_the_ID ();
And return the current post id by $_REQUEST then save it as meta value
It will return the id of current edited post not the current fronted post


if (isset($_REQUEST["post"]) && isset($_REQUEST["post"]) != '') {
$post_id = $_REQUEST["post"];


User183722 comments:

Thanks for your answer, but i also still not work. It was a good idea, but there no value...


User183722 comments:

I have done the following:

//Add Scripts + Styles Frontend
add_action('wp_enqueue_scripts','load_front_scripts');
function load_front_scripts($post_id){
$uploads = wp_upload_dir();
if (isset($_REQUEST["post"]) && isset($_REQUEST["post"]) != '') {
$post_id = $_REQUEST["post"];
}
wp_register_style('arti_carousel_post_front_css', trailingslashit($uploads['baseurl']) . 'arti-carousel/arti-carousel-post-'.$post_id.'.css', __FILE__);
wp_enqueue_style('arti_carousel_post_front_css');
wp_register_script('arti_carousel_post_front_js', trailingslashit($uploads['baseurl']) . 'arti-carousel/arti-carousel-post-'.$post_id.'.js', __FILE__);
wp_enqueue_script('arti_carousel_post_front_js');
}