php creating css class dynamically - php

I have a code which is completed and I want to add another code inside my completed code.
completed code:
function module( $prefix, $comma_seperated_suffixes ) {
foreach( (array)explode( ",", $comma_seperated_suffixes ) as $suffix ) {
$module_name = $prefix.trim($suffix);
if(count(JModuleHelper::getModules($module_name))) {
module_block($module_name);
}
}
}
I moved count(JModuleHelper::getModules($module_name)) to module function, previously it was in module_block
please dont use tovolt class, I mean simple code without php class
Module count block
i am assuming That I am calling this modules module("top-col-", "1,2,3"); then I have three modules called top-col-1, top-col-2, top-col-3
then my count module will look like this:
$TopCol1 = (int)(count(JModuleHelper::getModules($module_name)) > 0);
$TopCol2 = (int)(count(JModuleHelper::getModules($module_name)) > 0);
$TopCol3 = (int)(count(JModuleHelper::getModules($module_name)) > 0);
above code is will just count for active module (the only way to check active module), If a module is active then its var will be 1 .
and now the time to count active module:
$topColCount = $TopCol1 + $TopCol2 + $TopCol3;
if ($topColCount) : $TopColClass = 'count-' . $topColCount;
endif;
I am counting modules case I want to set a CSS class like this count-1, count-2, count-3 to active modules. and I want that class to be used in module_block.
please keep in mind that, above variable is static cause I made them manually. but if I call function then var need to be change with the function value like if user call module("bottom", "1,2,3"); then its count_modules will be $bottom1, $bottom2, $bottom3 and class will be $bottomClass.
I want to generate count_module using the same code module("bottom", "1,2,3");
Thanks #steve for your help

If I am understanding this correctly, this should help.
tovolt class: (note the new function 'prep_modules' added to this class)
<?php
////////////////// BEGIN CLASS tovolt
class tovolt{
function tovolt() {
//// constructor function - used to setup default variable states, etc. - if this is omitted PHP may have a fit ( depending on version and config )
}
public static $TopColClass = 'default-value';
function code_block( $jdoc_name ) {
?>
<div id="top-col" class="<?php echo self::$TopColClass; ?> columns">
<div class="panel">
<jdoc:include type="modules" name="<?php echo $jdoc_name; ?>" style="html5" />
</div>
</div>
<?php
}
function module( $prefix, $comma_seperated_suffixes ) {
foreach( (array)explode( ",", $comma_seperated_suffixes ) as $suffix ) {
$module_name = $prefix.trim($suffix);
self::code_block( $module_name );
}
}
////////////////// BEGIN NEW FUNCTIONS
function prep_modules( $MODULE_LIST ) {
$READY_MODULES = array();
foreach( (array)$MODULE_LIST as $module_name ) {
$MATCHED_MODULES = JModuleHelper::getModules($module_name);
$matched_count = count( $MATCHED_MODULES );
$matched_list = implode( ',', range( 1, $matched_count ) );
$READY_MODULES[$module_name] = array(
'MODULES' => $MATCHED_MODULES,
'count' => $matched_count,
'list' => $matched_list,
);
}
}
////////////////// END NEW FUNCTIONS
}
////////////////// END CLASS tovolt
?>
content page code - near top: (prepare this page's modules)
////////////////// SOMEWHERE BEFORE THE OUTPUT SECTION, LOAD MODULES FOR THIS PAGE
$READY_MODULES = tovolt::prep_modules( 'top', 'side', 'etc' );
content page code - content output area: ( choose the method that best fits your design )
method 1 - output a single section:
////////////////// DOWN IN THE MODULE OUTPUT SECTION - TO OUTPUT A SINGLE SECTION USE:
$section = 'top';
if( #$READY_MODULES[$section]['count'] > 0 ) {
tovolt::$TopColClass = $section; //// if you need to change: $TopColClass
tovolt::module( $section."-col-", $READY_MODULES[$section]['list'] );
}
method 2 - output all in order of loading:
////////////////// DOWN IN THE MODULE OUTPUT SECTION - TO OUTPUT ALL SECTIONS IN LOADED SEQUENCE USE:
foreach( (array)$READY_MODULES as $section=>$THIS_VAR_IS_NOT_DIRECTLY_REFERENCED ) {
if( #$READY_MODULES[$section]['count'] > 0 ) {
tovolt::$TopColClass = $section; //// if you need to change: $TopColClass
tovolt::module( $section."-col-", $READY_MODULES[$section]['list'] );
}
}
method 3 - arbitrary output:
////////////////// DOWN IN THE MODULE OUTPUT SECTION - TO OUTPUT MULTIPLE SECTIONS IN AN ARBITRARY ORDER:
foreach( array( 'side', 'top' ) as $section ) {
if( #$READY_MODULES[$section]['count'] > 0 ) {
tovolt::$TopColClass = $section; //// if you need to change: $TopColClass
tovolt::module( $section."-col-", $READY_MODULES[$section]['list'] );
}
}

Related

Hide main-component class in homepage

I have a template that has the feature to hide front-page component.
Unfortunately setting this feature to "hide" does hide the component but not the wrapper that surrounds it so, i need help to hide it manually in the home page only with id '101'.
The code that uses that feature is below:
function setMainContent() {
global $mainbody_block, $editmode, $side_block, $subnav, $active, $splitmenu_col, $leftcolumn_width, $rightcolumn_width, $mainmod2_width, $frontpage_component, $mainmod3_width;
$row = 'section-row3';
$cases = array(
'case3' => modulesClasses('case3'),
'case4' => modulesClasses('case4')
);
$this->maincontent = '<div id="section-row3" class="section-row"><div id="section-row3-inner">
<div id="main-body-surround" class="spacer">';
function mainbody($t, $c) {
global $mainbody_block, $leftcolumn_width, $mainmod2_width, $editmode, $frontpage_component, $mainmod3_width, $leftcolumn_width, $splitmenu_col, $subnav, $active;
$tmp = "";
$tmp .= '<div id="main-body" class="spacing">
<div class="module-'.$mainbody_block.'">';
$main = '
<div id="main-content">';
Is the best way to do this with php or css?

PHP widget use class selector instead of <tag> to build menu

I hope on of you clever chaps might be able to answer this riddle.
I have an excellent widget I am trying to integrate into my site. It creates menus from <H1>, <H2> etc, tags in the document. This is very useful as I can create sub menu navigation for each of my pages by styling the titles.
I am however using a wordpress theme that has extensions added to the editor that style various parts of the pages, including for example titles.
So the output from how it styles the title in HTML output is as follows for example:
<h1 class="grve-element grve-align-left grve-title-striped" style="">Visit</h1>
The PHP script I will load in below, the relevant section it appears to grab tags is:
$tags_to_parse = "<h1>";
Is there a way I can tell this PHP script to grab this particular H1 class?
Cheers,
Tomek
<?php
/*
Plugin Name: Anchors Menu
Description: Check Wordpress static pages content and create a widget menu with links that point to words between the HTML tags you chose.
Author: Gonçalo Rodrigues
Version: 1.2
Author URI: http://www.goncalorodrigues.com
*/
/* Copyright 2010 Gonçalo Rodrigues (email : gonafr [AT] gmail [DOT] com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
//ERROR_REPORTING(E_ALL);
$count = -1;
add_action("init", "anc_insert_init");
add_filter("the_content", "anc_add_link_text");
// renders the list in your theme;
function anc_insert()
{
$tags_to_parse = "<h1>";
$current_page_id = get_the_ID();
$page_data = get_page($current_page_id);
$current_page_name = $page_data->post_name;
$current_page_cat_id = get_cat_ID($current_page_name);
$page_id = get_the_ID();
// if it's blog style page
if (is_home()){
$count = 0;
$content = "";
if ( have_posts() ) : while ( have_posts() ) : the_post();
$id_post = get_the_ID();
$post = get_post($id_post);
$content .= "<a name=\"$count\"></a>";
$content .= $post->post_content;
$count++;
endwhile; else:
//_e("Sorry, no posts matched your criteria.");
endif;
anc_list_menu($content);
//echo "Sorry but this plugin only work on Wordpress pages.";
}
//if it's page style page
else if(is_page()){
$page_id = get_the_ID();
$page_data = get_page( $page_id );
//$title = $page_data->post_title; // Get title
$content = $page_data->post_content;
//if content is empty i will fetch all pages that are child of the current page and get their titles
$fetch_children_pages = true;
if (fetch_children_pages == true && $content==""){
$content = "";
$pages = get_pages('child_of='.$page_id.'&sort_column=post_date&sort_order=desc');
foreach($pages as $page)
{
$content .= "<".$tags_to_parse.">".$page->post_title."</".$tags_to_parse.">";
if(!$content)
continue;
$count++;
}
}
anc_list_menu($content);
}
// if it's single post
else if (is_single()){
$content = "";
$content .= get_the_content();
anc_list_menu($content);
//echo "Sorry but this plugin only work on Wordpress pages.";
}
//if it's a category page
else if(is_category){
//echo $current_page_cat_id;
//echo $current_page_name;
//echo $current_page_id;
$current_cat = get_the_category();
//echo 'teste'.$current_cat[0]->cat_name;
$current_cat_id = get_cat_ID($current_cat[0]->cat_name);
$posts = get_posts('$category_name='.$current_cat[0]->cat_name);
$content = "";
if ( have_posts() ) : while ( have_posts() ) : the_post();
$id_post = get_the_ID();
$post = get_post($id_post);
$content .= "<".$tags_to_parse.">".$post->post_title."</".$tags_to_parse.">";
endwhile; else:
//_e("Sorry, no posts matched your criteria.");
endif;
anc_list_menu($content);
//echo "Sorry but this plugin only work on Wordpress pages.";
}
else {
//_e("Error: This page is not a tradicional Wordpress Page or a Wordpress Blog!");
}
}
// prints the menu with the links to the titles
function anc_list_menu($content){
// list all tags
$foo_tags = anc_get_tags($content);
if($foo_tags[1] != 0){
$foo = -1;
echo "<ul>";
foreach($foo_tags[0] as $key => $val){
$foo++;
echo "<li>".$val."</li>";
}
echo "</ul>";
}else{
//no tags found
//_e("Not found any tag of the type that was selected to be parsed.");
}
}
// retrieve all words between tags
function anc_get_tags($content){
global $tags_to_parse;
$options = get_option("anc_tags");
$tags_to_parse = $options["anc_tags"];
$pattern_search = "/(<".$tags_to_parse.".*>)(.*)(<\/".$tags_to_parse.">)/isxmU";
preg_match_all($pattern_search, $content, $patterns);
$res = array();
array_push($res, $patterns[2]);
array_push($res, count($patterns[2]));
return $res;
}
// insert widget
function anc_insert_init()
{
//register the widget
register_sidebar_widget("Anchors Menu", "anc_widget_insert");
//register the widget control
register_widget_control("Anchors Menu", "anc_widget_insert_control");
}
function anc_widget_insert($args) {
global $title, $tags_to_parse;
extract($args);
//get our options
$options = get_option("anc_title");
$title = $options["anc_title"];
$options = get_option("anc_tags");
$tags_to_parse = $options["anc_tags"];
echo $before_widget;
/*Insert any headers you want in the next line, between "?>" and "<?". Leave blank for no header. */
echo $before_title . $title . $after_title;
anc_insert();
echo $after_widget;
}
// responsable for options in backoffice
function anc_widget_insert_control() {
global $title, $tags_to_parse;
//get saved options if user change things
//handle user input
if (isset($_POST["anc_insert_submit"])){
$foo_title = strip_tags(stripslashes($_POST["anc_title"]));
$foo_tags = strtolower(stripslashes($_POST["anc_tags"]));
$options["anc_title"] = $foo_title;
$options["anc_tags"] = $foo_tags;
update_option("anc_title", $options);
update_option("anc_tags", $options);
}
else {
//default options
$options["anc_title"] = "Menu";
$options["anc_tags"] = "h2";
update_option("anc_title", $options);
update_option("anc_tags", $options);
}
//get our options
$options = get_option("anc_title");
$title = $options["anc_title"];
$options = get_option("anc_tags");
$tags_to_parse = $options["anc_tags"];
//print the widget control
include("anc-insert-widget-control.php");
}
// adds anchors to content tags
function anc_add_link_text($content){
global $tags_to_parse, $count;
$options = get_option("anc_tags");
$tags_to_parse = $options["anc_tags"];
$pattern_search = array();
$pattern_search = "/(<".$tags_to_parse.".*>)(.*)(<\/".$tags_to_parse.">)/isxmU";
return preg_replace_callback($pattern_search, "anc_replacement", $content, -1);
}
// aux funtion to add_link_text
function anc_replacement($matches){
global $tags_to_parse, $count;
$count++;
return "<a name=\"".$count."\"></a>"."<".$tags_to_parse.">".$matches[2]."</".$tags_to_parse.">";
}
?>
Replace your $pattern_search variable with this:
$pattern_search = "/(<h1 .*(".$tags_to_parse.")+ .*>)+(.*)+(<\/h1>)/isxmU";
Now you can pass class to your function:
$tags_to_parse = "grve-element";
Update
$tags_to_parse = "grve-element";
$content = '<h1 class="grve-element grve-align-left grve-title-striped" style="">Visit</h1>sf efew <h1 grve-element>rffef</h1>';
$pattern_search = "/\<h1 .(".$tags_to_parse.")?[^\>]*\>(.*?)\<\/h1\>/";
preg_match_all($pattern_search, $content, $patterns);
print_r($patterns[2]);
Output
Array ( [0] => Visit [1] => rffef )

Strict standards: Only variables should be assigned by reference in C: when trying to use an older extension on MW 1.22.1

The way I have my wiki set up I need an extension that allows breadcrumbs to work and not duplicate , as well as, shrink when you go back a page. I cannot use subpage breadcrumb extensions. I would appreciate it if anyone who has a good eye for fixing code, would be able to adjust this code so that I do not get the Strict standards: Only variables should be assigned by reference in C: It occurs on line 109:
$m_skin =& $wgUser->getSkin();
Thank you in advance!
<?php
# The BreadCrumbs extension, an extension for providing an breadcrumbs
# navigation to users.
# #addtogroup Extensions
# #author Manuel Schneider <manuel.schneider#wikimedia.ch>
# #author Kimon Andreou
# #copyright © 2007 by Manuel Schneider, Kimon Andreou
# #licence GNU General Public Licence 2.0 or later
if( !defined( 'MEDIAWIKI' ) ) {
echo( "This file is an extension to the MediaWiki software and cannot be used
standalone.\n" );
die();
}
## Options:
# set the delimiter
$wgBreadCrumbsDelimiter = ' > ';
# number of breadcrumbs to use
$wgBreadCrumbsCount = 5;
$bcBreadCrumbs = new BreadCrumbs();
$wgExtensionFunctions[] = array($bcBreadCrumbs, 'setup');
$wgHooks['UserToggles'][] = array($bcBreadCrumbs, 'toggle');
$wgExtensionCredits['parserhook'][] = array(
'name' => 'BreadCrumbs',
'author' => 'Kimon Andreou',
'url' => 'http://www.mediawiki.org/wiki/Extension:BreadCrumbs_(Kimon)',
'description' => "Shows a breadcrumb navigation. Based heavily on Manuel Shneider's
extension[http://www.mediawiki.org/wiki/Extension:BreadCrumbs]"
);
##
## Main class
class BreadCrumbs {
#constructor
function BreadCrumbs() {}
## Set Hook:
function setup() {
global $wgUser, $wgHooks;
## Showing and updating the breadcrumbs trail
# Hook when viewing article header:
$wgHooks['ArticleViewHeader'][] = array($this, 'show');
## Infrastructure
# Hook our own CSS:
$wgHooks['OutputPageParserOutput'][] = array($this, 'output');
}
#Return our new user preference (t/f toggle)
function toggle(&$arr) {
global $wgMessageCache;
#named "breadcrumb" - original, no?
$arr[] = 'breadcrumb';
$wgMessageCache->addMessage('tog-breadcrumb', 'Use breadcrumbs');
return true;
}
#Show the breadcrumbs on the page
function show( &$m_pageObj ) {
global $wgUser, $wgTitle, $wgOut, $wgBreadCrumbsDelimiter, $wgBreadCrumbsCount;
# deserialize data from session into array:
$m_BreadCrumbs = array();
#If a session doesn't already exist, create one
if( isset( $_SESSION['BreadCrumbs'] ) ) {
$m_BreadCrumbs = $_SESSION['BreadCrumbs'];
}
else {
if( !isset( $_SESSION ) ) {
session_start();
}
$_SESSION['BreadCrumbs'] = array();
}
# cache index of last element:
$m_count = count( $m_BreadCrumbs ) - 1;
# if we've got too many entries, reduce the array:
if( count( $m_BreadCrumbs ) > 0 && $m_BreadCrumbs[ $m_count ] !=
$wg Title->getPrefixedText() ) {
# reduce the array set, remove older elements:
$m_BreadCrumbs = array_slice( $m_BreadCrumbs, ( 1 - $wgBreadCrumbsCount ) );
# add new page:
array_push( $m_BreadCrumbs, $wgTitle->getPrefixedText() );
}
else {
array_push( $m_BreadCrumbs, $wgTitle->getPrefixedText() );
}
#if returning to a page we've already visited, reduce the array
$loc = array_search($wgTitle->getPrefixedText(), $m_BreadCrumbs);
if(($loc >= 0)) {
#shrink array
$m_BreadCrumbs = array_slice($m_BreadCrumbs, 0, ($loc + 1));
}
# serialize data from array to session:
$_SESSION['BreadCrumbs'] = $m_BreadCrumbs;
# update cache:
$m_count = count( $m_BreadCrumbs ) - 1;
# acquire a skin object:
$m_skin =& $wgUser->getSkin();
# build the breadcrumbs trail:
$m_trail = "<div id=\"BreadCrumbsTrail\"> <i>Bread crumbs:</i> ";
for( $i = 1; $i <= $m_count; $i++ ) {
$m_trail .= $m_skin->makeLink( $m_BreadCrumbs[$i] );
if( $i < $m_count ) $m_trail .= $wgBreadCrumbsDelimiter;
}
$m_trail .= ' </div>';
$wgOut->addHTML( $m_trail );
# invalidate internal MediaWiki cache:
$wgTitle->invalidateCache();
$wgUser->invalidateCache();
# Return true to let the rest work:
return true;
}
## Entry point for the hook for printing the CSS:
# todo: find a better implementation
function output( &$m_pageObj, &$m_parserOutput ) {
global $wgScriptPath;
# Register CSS file for our select box:
$m_pageObj->addLink(
array(
'rel' => 'stylesheet',
'type' => 'text/css',
'href' => $wgScriptPath . '/extensions/BreadCrumbs/BreadCrumbs.css'
)
);
# Be nice:
return true;
}
}
?>'
I have removed $userName from line 1098 on Linker.php after following what Sammitch suggested:
public static function userLink( $userId, $userName, $altUserName = false ) {
if ( $userId == 0 ) {
$page = SpecialPage::getTitleFor( 'Contributions', $userName );
if ( $altUserName === false ) {
$altUserName = IP::prettifyIP( $userName );
}
} else {
$page = Title::makeTitle( NS_USER, $userName );
}
return self::link(
$page,
htmlspecialchars( $altUserName !== false ? $altUserName : $userName ),
array( 'class' => 'mw-userlink' )
);
}
This allows the breadcrumbs to show without any errors. However, now the pages do not show in breadcrumb links. I just have > > > as though the pages go in between the arrows. Can anyone take it from here and find out how to get the pages to appear? Was removing the $userName the cause of this?
Thanks
This extension is originally based on Breadcrumbs, which has been kept up to date: https://www.mediawiki.org/wiki/Extension:BreadCrumbs
Looking that that code, the links are now being made by calling the linker directly:
$title = Title::newFromText( $m_BreadCrumbs[$j] );
$breadcrumb = Linker::link( $title, $m_BreadCrumbs[$j] );
So adapting that to the older code:
$title = Title::newFromText( $m_BreadCrumbs[$i] );
$m_trail .= Linker::link( $title, $m_BreadCrumbs[$i] );
Should work for you. However, that may not be the last bit of deprecated code you run into with this old extension. It might be a good idea to look at moving to the maintained BreadCrumbs extension, instead - or at least compare the code you find there and see what other changes might be needed to get this one up to speed.

Template Library

I'm trying to use a template library created by Phil Sturgeon. He has some great documentation for his template library but I've ran into a little bit of a problem with how I have my file structure done.
-views
-layouts
-default.php
-partials
-header_view.php
-footer_view.php
-metadata_view.php
login_view.php
Inside of my login controller index function I have the following code to establish which layout to use and which view to load as the body of the template. I also have included what I have inside of the header_view.php file which I believe is what I'm not getting to work right. I was hoping to be able to target the metadata partial inside of the header_view. According to the documentation I'm doing it correctly, however, I'm getting an error undefined index metadata coming from the header_view.php file. Any light on this issue.
Documention from the github repostitory: https://github.com/philsturgeon/codeigniter-template
$this->template
->title('Login Form')
->set_partial('header', 'partials/header_view')
->set_partial('metadata', 'partials/metadata_view')
->set_partial('footer', 'partials/footer_view')
->set_layout('default')
->build('login_form_view');
default.php
<?php echo $template['partials']['header']; ?>
<?php echo $template['body']; ?>
<?php echo $template['partials']['footer']; ?>
header_view.php
<!DOCTYPE html>
<html>
<head>
<title><?php echo $template['title']; ?></title>
<?php echo $template['partials']['metadata']; ?>
</head>
<body
well im a codeigniter fan; and i honestly think that the real power of CI that it doesnt come loaded with fancy "TEMPLATING lib" or auth lib; yet it give you all tools to build your own swiftly and very rappidly;
so my answer my not be what you really asking for but its a simple example of how you can build your own so called templaling lib in ci in less than 10mins and works flowlessly;
create MY_Controller inside applicaiton/core folder;
class MY_Controller extends CI_Controller {
protected $noEcho=true,$body = 'base/layout', $title = 'YOUR CONTROLLER TITLE',
$js = array(), //filename
$inline_js = '', //script
$css = array(),
$inline_css = '', //style
$content = array(); //html
inside it will be 3 basic functions
that set you page parts;
that manage your assets
that print out your end result page;
1
function output($data,$section='content'){
//checking type of data to be pushed its either array or string(html)
//this is a view it should be formated like this array( viewname,$data )
if( is_array($data) ){
$this->content[ $section ][] = $this->load->view( $data[0], $data[1], TRUE );
return $this;//to allow chaing
}elseif( is_string($data) ){//this is html
$this->content[ $section ][] = $data;
return $this;//to allow chaing
}
}
2nd is a function that let you add js,css and and inline js&css to this page;
function _asset( $link, $txt = FALSE ) {
if ( $txt !== FALSE ) {
if ( $txt == 'js' )
$this->inline_js[] = $txt;
elseif ( $txt == 'css' )
$this->inline_css[] = $txt;
}else{
if ( pathinfo( $link, PATHINFO_EXTENSION ) == 'css' ){
$this->css[] = link_tag( base_url( 'assets/css/' . trim( $link, "/\\" ) ) );
}else{
$this->js[] = '<script src="' . base_url( 'assets/js/' . trim( $link, "/\\" ) ) . '"></script>';
}
}
return $this;
}
and at last a function that put all your parts together;
protected function print_page(){
if ( $this->noEcho ) ob_clean();
$data=array();
$data[ 'title' ] = $this->title;
$data[ 'css' ] = is_array( $this->css ) ? implode( "\n", $this->css ) : '';
$data[ 'js' ] = is_array( $this->js ) ? implode( "\n", $this->js ) : '';
$data[ 'inline_css' ] = ( $this->inline_css ) ? '<style>' . implode( "\n", $this->inline_css ) . '</style>' : '';
$data[ 'inline_js' ] = ( $this->inline_js ) ? implode( "\n", $this->inline_js ) : '';
foreach ( $this->content as $section => $content ) {
$data[ $section ] = is_array( $content ) ? implode( "\n\n\n ", $content ) : $content;
} //$this->content as $section => $content
return $this->load->view( $this->body, $data );
}
now put all three together and extend your controller to this base controller;
now for the example page your are trying to build i would do:
Controller :
public function __construct() {
parent::__construct();
$this->title = 'Controller title';
$this->body = 'base/default';
//load all your assets.. if its across all pages then load them in MY_controller construct
$this->assets('jquery.min.js')
->assets('bootstrap.css')
->assets('alert("itworks");','js');//will be added to $inline_js
}
function index(){
$var = $This->some_model->get_data();
$this->output( array('some_View',$var) )
->output('<hr/>')
->output('THIS WILL BE IN $FOOTER','footer')
->print_page();
}
Now how clean is that :) ?;
now your controller will load view set on this->body and all pass all your sections to it.
so for above example your view will recieve 2 variables.
$content : ill contail some_view view +
$footer : will contain html we passed it to it;
$css,$js,$inline_js,$inline_css variables contain all you assets
$title contain your page title;
at end
i hope that i hope this small demo help you understand the unlimited possibilities that these 3 small functions can do thanks to CI native view loader.

Insert PHP code In WordPress Page and Post

I want to know the visitor country using PHP and display it in on a WordPress Page. But when I add PHP code to a WordPress page or post it gives me an error.
How can we add PHP code on WordPress pages and posts?
<?PHP
try
{
function visitor_country()
{
$client = #$_SERVER['HTTP_CLIENT_IP'];
$forward = #$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
$result = "Unknown";
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
$ip_data = #json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
if($ip_data && $ip_data->geoplugin_countryName != null)
{
$result = array('ip' => $ip,
'continentCode' => $ip_data->geoplugin_continentCode,
'countryCode' => $ip_data->geoplugin_countryCode,
'countryName' => $ip_data->geoplugin_countryName,
);
}
return $result;
}
$visitor_details = visitor_country(); // Output Country name [Ex: United States]
$country = $visitor_details['countryName'];
WordPress does not execute PHP in post/page content by default unless it has a shortcode.
The quickest and easiest way to do this is to use a plugin that allows you to run PHP embedded in post content.
There are two other "quick and easy" ways to accomplish it without a plugin:
Make it a shortcode (put it in functions.php and have it echo the country name) which is very easy - see here: Shortcode API at WP Codex
Put it in a template file - make a custom template for that page based on your default page template and add the PHP into the template file rather than the post content: Custom Page Templates
You can't use PHP in the WordPress back-end Page editor. Maybe with a plugin you can, but not out of the box.
The easiest solution for this is creating a shortcode. Then you can use something like this
function input_func( $atts ) {
extract( shortcode_atts( array(
'type' => 'text',
'name' => '',
), $atts ) );
return '<input name="' . $name . '" id="' . $name . '" value="' . (isset($_GET\['from'\]) && $_GET\['from'\] ? $_GET\['from'\] : '') . '" type="' . $type . '" />';
}
add_shortcode( 'input', 'input_func' );
See the Shortcode_API.
Description:
there are 3 steps to run PHP code inside post or page.
In functions.php file (in your theme) add new function
In functions.php file (in your theme) register new shortcode which call your function:
add_shortcode( 'SHORCODE_NAME', 'FUNCTION_NAME' );
use your new shortcode
Example #1: just display text.
In functions:
function simple_function_1() {
return "Hello World!";
}
add_shortcode( 'own_shortcode1', 'simple_function_1' );
In post/page:
[own_shortcode1]
Effect:
Hello World!
Example #2: use for loop.
In functions:
function simple_function_2() {
$output = "";
for ($number = 1; $number < 10; $number++) {
// Append numbers to the string
$output .= "$number<br>";
}
return "$output";
}
add_shortcode( 'own_shortcode2', 'simple_function_2' );
In post/page:
[own_shortcode2]
Effect:
1
2
3
4
5
6
7
8
9
Example #3: use shortcode with arguments
In functions:
function simple_function_3($name) {
return "Hello $name";
}
add_shortcode( 'own_shortcode3', 'simple_function_3' );
In post/page:
[own_shortcode3 name="John"]
Effect:
Hello John
Example #3 - without passing arguments
In post/page:
[own_shortcode3]
Effect:
Hello
When I was trying to accomplish something very similar, I ended up doing something along these lines:
wp-content/themes/resources/functions.php
add_action('init', 'my_php_function');
function my_php_function() {
if (stripos($_SERVER['REQUEST_URI'], 'page-with-custom-php') !== false) {
// add desired php code here
}
}

Categories