Wordpress Buffer HTML Cache - php

I'm writing a plugin that writes the HTML output to the file and loads the site from that file, next time. It works flawlessly. But I can't cache the code after the wp_footer hook. I tried the "shutdown" hook that works after the wp_footer hook but it returns null. I don't know why it is returning null. But I need a hook that runs after the wp_footer hook, where I can cache all the code from 0 to 100.
<?php
$priority = 10;
add_action('template_redirect', function(){
if(!is_admin() && !is_user_logged_in()){
$cache_time = get_option('html_cache_time');
if(empty($cache_time)){
$cache_time = 60;
}
$current_url = get_site_url() . $_SERVER['REQUEST_URI'];
if(filter_var($current_url, FILTER_SANITIZE_URL)){
$parsed_url = parse_url($current_url);
$url_path = isset($parsed_url['path']) ? $parsed_url['path'] : false;
if(!empty($url_path)){
$cached_url = NGY_CACHE_DIR . 'app/cached/' . md5($url_path) . '.cache';
define('NOGAY_CACHED_URL', $cached_url);
$end_time = 60 * $cache_time;
if(file_exists($cached_url)){
if(time() - $end_time < filemtime($cached_url)){
readfile($cached_url);
exit;
}else{
unlink($cached_url);
}
}
}
}
ob_start();
}
}, $priority);
add_action('wp_footer', function(){
if(!is_admin() && !is_user_logged_in()){
$html = ob_get_clean();
if(!file_exists(NOGAY_CACHED_URL)){
echo $html;
}
$open_cached_file = fopen(NOGAY_CACHED_URL, 'w+');
fwrite($open_cached_file, $html);
fclose($open_cached_file);
ob_end_flush();
}
}, PHP_INT_MAX);
I tried another Wordpress hooks. (shutdown)

Related

Get variable from a page to index page in wordpress

I have a variable called $total in a page called page-pants.php,
i need to echo the variable called $total in index.php page.
how it can be done?
Best thing to use is a non expiring transient. Set your $total with the following code in your page-pants.php file. I am assuming that the $total value is changing each time you visit the pants page.
delete_transient( 'pants_total' );
// Save $total as the transient pants_total
set_transient( 'pants_total', $total );
Then you can access the $total anywhere in your WordPress site with the following
$total = get_transient( 'pants_total' );
echo $total;
You can define and set that in your functions.php and use that in everywhere that you need.
For example:
add_action('init', 'myStartSession', 1);
add_action('wp_logout', 'myEndSession');
add_action('wp_login', 'myEndSession');
function myStartSession() {
if(!session_id()) {
session_start();
}
$_SESSION['myKey'] = "Some data I need later";
}
function myEndSession() {
session_destroy ();
}
And show that in each theme file that you need:
if(isset($_SESSION['myKey'])) {
$value = $_SESSION['myKey'];
} else {
$value = '';
}
echo $value;

Shortcode output shown at the top of the page

I know this question is similar to other questions that have been posted. I have followed exactly what was suggested in answers to those questions but still can't figure out why the output is shown at the the top of the page.
function foo_shortcode($atts, $content = null) {
$datashortcode = '<div>'.(function_exists('rtb_kk') ? rtb_kk() : '').'</div>';
return $datashortcode;
}
add_shortcode('showfoo', 'foo_shortcode');
Any idea?
Without knowing how the rtb_kk() function works, I can only assume it uses echo to display content rather than using return. This is what causes the output of that function to appear at the top of the page.
To work around this issue, you can capture the output of the function with ob_start() and ob_get_clean():
function foo_shortcode($atts, $content = null) {
if (function_exists('rtb_kk')) {
// Start output buffering
ob_start();
// Run the function
rtb_kk();
// Capture buffer as a string
$output = ob_get_clean();
} else {
// Function doesn't exist so we return an empty string
$output = '';
}
return '<div>' . $output . '</div>';
}
add_shortcode('showfoo', 'foo_shortcode');
Alternative method
If you're able to use the bcn_display() instead of the rtb_kk() method you're using, then there is no need to rely on ob_get_clean().
function foo_shortcode($atts, $content = null) {
if (function_exists('bcn_display')) {
// Return the output as a string so we can control when it's displayed
$output = bcn_display( true );
} else {
// Function doesn't exist so we return an empty string
$output = '';
}
return '<div>' . $output . '</div>';
}
add_shortcode('showfoo', 'foo_shortcode');
This will solve your problem, just try
<script type="text/javascript">
function foo_shortcode($atts, $content = null) {
if(function_exists('rtb_kk')){
$rtb_kk = rtb_kk();
}else{
$rtb_kk = '';
}
$datashortcode = "<div>$rtb_kk</div>";
return $datashortcode;
}
add_shortcode('showfoo', 'foo_shortcode');
</script>

how can I load a stylesheet with php if the page is not home?

I am trying to exclude a css file from the home page of my site. We load the stylesheet with the header.php, so I am trying to not load it in the homepage.
this is my following code.
$hm == 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if ($hm == "home.php") {
echo "";
} else {
echo "yesstylesheet.css";
}
If do you mean home page - main page of your site, than you can try to use follow code
if ($_SERVER['REQUEST_URI']!="/")
{
echo "connect ccs here";
}
Use this snippet
$hm = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$hm1 = strrev($hm);
$hm2 = substr($hm1, strpos($hm1, "/") + 1);
$hm3 = "/".$hm2;
$hm4 = str_replace($hm3,"",$hm1);
$hm = strrev($hm4);
if ($hm == "home.php") {
echo "";
} else {
echo "yesstylesheet.css";
}

Adding schema to meta <head>-tag: wordpress

I am trying to put this (below code) to my wordpress header but when i save and load site on browser it does not show up. I have seen this schema practice on some wordpress themes so it should work. Does anyone have advice? Is it some automatic wordpress function that changes this.
<head itemscope="" itemtype="http://schema.org/WebSite">
do it like this on your header.php
<html <?php html_tag_schema(); ?> <?php language_attributes(); ?>>
and you need to write the function html_tag_schema() now. write the below function on your active theme's functions.php
function html_tag_schema()
{
$schema = 'http://schema.org/';
// Is single post
if(is_single())
{
$type = "Article";
}
// Contact form page ID
else if( is_page(1) )
{
$type = 'ContactPage';
}
// Is author page
elseif( is_author() )
{
$type = 'ProfilePage';
}
// Is search results page
elseif( is_search() )
{
$type = 'SearchResultsPage';
}
// Is of movie post type
elseif(is_singular('movies'))
{
$type = 'Movie';
}
// Is of book post type
elseif(is_singular('books'))
{
$type = 'Book';
}
else
{
$type = 'WebPage';
}
echo 'itemscope="itemscope" itemtype="' . $schema . $type . '"';
}
I hope this one solves your problem

Simple PHP Controller, any issues with this code?

I'm trying to build a really simple php controller page for a small site. Here is what I have so far. It seems to work well. Are there any issues I might be missing with doing it this way?
$page = $_GET['p'];
switch ($page)
{
case "":
ob_start();
include "inc/home.php";
$content = ob_get_contents();
ob_end_clean();
break;
case $page:
$page = str_replace("/", "", $page);
if (file_exists("inc/".$page.".php"))
{
ob_start();
include "inc/".$page.".php";
$content = ob_get_contents();
ob_end_clean();
}
else
include "inc/404.php";
break;
}
include("inc/header.php");
echo $content;
include("inc/footer.php");
UPDATE: Here is the final code based on comments that works well.
<?php
$page = (isset( $_GET['p']) && !empty($_GET['p'])) ? $_GET['p'] : 'home';
if( preg_match( '/[^a-z]/i', $page))
{
$page = '404';
}
if( !file_exists( "inc/".$page.".php"))
{
$page = '404';
}
ob_start();
include("inc/header.php");
include("inc/".$page.".php");
include("inc/footer.php");
?>
Your entire script can be rewritten as follows:
$page = ( isset( $_GET['p']) && !empty( $_GET['p'])) ? $_GET['p'] : 'home';
// Only allow alphabetic characters in a user supplied page
if( preg_match( '/[^a-z]/i', $page))
{
$page = '404';
}
if( !file_exists( "inc/".$page.".php"))
{
$page = '404';
}
include("inc/header.php");
include("inc/".$page.".php");
include("inc/footer.php");
However, this is also no longer susceptible to Local File Inclusion, as $page is restricted to only alphabetic characters, and the script will show the 404 page if anything else is submitted.
It's also more efficient as its not using output buffering.

Categories