Wordpress - custom page template will not assign to page - php

First time building a Wordpress plugin. I create a page and I want to assign it a page template from my plugin folder. My code shows the Template name in the selectable list in the page editor, but it is not attached to the page. Nor manually attaching does anything to the page. But the path for the file is correct.
My code to create a page:
$page_path = "this-is-a-campaign-landing-page";
$page_title = 'This is a Campaigns Page Title';
$page_content = 'THIS IS A CAMPAIGNS PAGE BODY';
$page_check = get_page_by_title( $page_path );
$page = array(
'post_type' => 'page',
'post_title' => $page_title,
'post_content' => $page_content,
'post_status' => 'publish',
'post_author' => $author->ID,
'post_slug' => $page_path
);
if (!isset($page_check->ID) && !get_page_by_path($page_path)) {
$page_id = wp_insert_post($page);
if ($page_id) {
$template = '/home/vagrant/src/wptest/wp-content/plugins/pm/campaign_page.php';
update_post_meta($page_id, '_wp_page_template', $template );
}
}
Separately I add the template with add_filters
function add_campaign_template ($templates) {
$templates['campaign_page.php'] = 'Campaign Page';
return $templates;
}
add_filter ('theme_page_templates', 'add_campaign_template');
function set_campaign_template ($template) {
if ('campaign_page.php' == basename ($template)) {
$template = '/home/vagrant/src/wptest/wp-content/plugins/pm/campaign_page.php';
}
return $template;
}
add_filter ('page_template', 'set_campaign_template');
The page creates with no errors. When I view or edit the page, Default template is selected and my template appears in the list. Selecting it manually has no effect. What did I miss?
My simple page template:
<?php
/**
* Template Name: Campaign Page
*
* #package PM
*/
// get_header();
?>
<div id="primary" class="content-area">
<main id="main" class="site-main">
<section class="outer-categories">
<div class="container-fluid">
<div class="row text-justify">
THIS IS THE RIGHT PAGE TEMPLATE
THIS IS THE RIGHT PAGE TEMPLATE
THIS IS THE RIGHT PAGE TEMPLATE
THIS IS THE RIGHT PAGE TEMPLATE
<div class="col-lg-12">
<?php
while ( have_posts() ) :
the_post();
get_template_part( 'template-parts/content', 'page' );
endwhile; // End of the loop.
?>
</div>
</div>
</div>
</section>
</main><!-- #main -->
</div><!-- #primary -->
<?php
// get_footer();
Why is it not adding the template? With debug on I get no error in debug.log

Wow, long day.
Change this:
function set_campaign_template ($template) {
if ('campaign_page.php' == basename ($template)) {
$template = '/home/vagrant/src/wptest/wp-content/plugins/pm/campaign_page.php';
}
return $template;
}
add_filter ('page_template', 'set_campaign_template');
to this:
function set_campaign_template ($template) {
if ('campaign_page.php' == basename ($template)) {
$template = 'campaign_page.php'; <---- FIX
}
return $template;
}
add_filter ('page_template', 'set_campaign_template');

Related

WordPress is redirecting to home page in custom template

I am loading custom template via template_include to load single page of a type. But it redirects to home page if a static page is selected as homepage from Settings > Reading
But it works if Your latest posts is selected.
Here is my code
add_filter( "template_include", "change_template" );
function change_template ($template) {
if ( !is_page("game") && preg_match('/\/game\//',$_SERVER["REQUEST_URI"] ) ) {
remove_filter( 'template_redirect' );
$template = PLUGIN_ROOT . "single-game.php";
if ( file_exists( $template ) ) {
return $template;
exit;
}
}
return $template;
}
and single-game.php includes this
<?php get_header();?>
<div id='game-root'> </div>
<?php get_footer(); ?>

Wordpress how to auto-generat pages programmatically when custom WordPress theme is installed and assign them to blog page and front page

So I have a Custom WordPress Theme I am developing and upon installation of it in a new WordPress setup I would like a MENU auto-generated along with 3 pages, i.e:
Products
Policy
Services
that is my theme will heavily depend on.
I will already have 3 template pages made for these in the custom theme files, i.e:
page-products.php
page-policy.php
page-services.php
So when the theme is installed these are auto-created so it's a no brainer for the client.
I know Twig but very little PHP and if some could write this up so I could just drop it into my functions.php file.
I would be very, very grateful and many thanks!!
EDIT
Additional questions
Also I will be having a Home and a News page auto created as well. Would there be a quick code to auto set these up as the default Homepage and default Posts page? Or is it more complicated than that?
You could use after_switch_theme action hook and wp_insert_post function to achieve what you're looking for.
after_switch_themeDocs
wp_insert_postDocs
So to generate these three pages, first, we create a function that incorporates wp_insert_post function. Our custom function will take two arguments and first checks whether the page you're trying to create exists or not. If the page exists it will return false, otherwise, it'll create the page and return the id of that page.
The following code goes to the functions.php file of your active theme.
function your_theme_create_page($page_title, $page_content)
{
$page_obj = get_page_by_title($page_title, 'OBJECT', 'page');
if ($page_obj) {
return false;
exit();
}
$page_args = array(
'post_type' => 'page',
'post_status' => 'publish',
'post_title' => ucwords($page_title),
'post_name' => strtolower(trim($page_title)),
'post_content' => $page_content,
);
$page_id = wp_insert_post($page_args);
return $page_id;
}
Now, on after_switch_theme action hook we run another custom function. This time we will create an associative array to hold our page titles as well as page contents. Then we feed that array to the function we created above using a foreach loop.
The following code also goes to the functions.php of your active theme.
add_action('after_switch_theme', 'my_custom_pages_on_theme_activation');
function my_custom_pages_on_theme_activation()
{
$pages_array = array(
'products page' => '<h3>Hello from products page</h3>',
'policy page' => '<h3>Hello from policy page</h3>',
'services page' => '<h3>Hello from services page</h3>'
);
foreach ($pages_array as $page_title => $page_content) {
$current_page = your_theme_create_page($page_title, $page_content);
if (false != $current_page) {
add_action('admin_notices', function () use ($page_title) {
?>
<div class="notice notice-success is-dismissible">
<p><?php echo "Done! {$page_title} has been created"; ?></p>
</div>
<?php
});
} else {
add_action('admin_notices', function () use ($page_title) {
?>
<div class="notice notice-warning is-dismissible">
<p><?php echo "{$page_title} was not created! Check whether it already exists"; ?></p>
</div>
<?php
});
}
}
}
Note that i used admin_notices action hook to give the user a visual message.
if generating those pages was successful, then user sees the following messages:
If, on the other hand, those pages were not generated or they already exist, then the user will see the following messages:
Now we have our pages created, you could see them on the pages menu on the admin screen:
And here's the page content for example:
Now, you could take this one step further and create more complex templates and feed them to that assortative array.
So for example, you have page-products.php, page-policy.php and page-services.php files inside a folder called, let's say, inc. So your folder structure would be something like this:
Your-theme-folder
|
|css-folder
| |
| some-css.css
|
|javascript-folder
| |
| some-js.js
|
|inc-folder
|
page-products.php
page-policy.php
page-services.php
Then your associative array would be something like this:
add_action('after_switch_theme', 'my_custom_pages_on_theme_activation');
function my_custom_pages_on_theme_activation()
{
$products_page_title = 'products page';
$policy_page_title = 'policy page';
$services_page_title = 'services page';
$products_page_content = file_get_contents(__DIR__ . '\inc\page-products.php');
$policy_page_content = file_get_contents(__DIR__ . '\inc\page-policy.php');
$services_page_content = file_get_contents(__DIR__ . '\inc\page-services.php');
$pages_array = array(
$products_page_title => $products_page_content,
$policy_page_title => $policy_page_content,
$services_page_title => $services_page_content
);
foreach ($pages_array as $page_title => $page_content) {
$current_page = your_theme_create_page($page_title, $page_content);
if (false != $current_page) {
add_action('admin_notices', function () use ($page_title) {
?>
<div class="notice notice-success is-dismissible">
<p><?php echo "Done! {$page_title} has been created"; ?></p>
</div>
<?php
});
} else {
add_action('admin_notices', function () use ($page_title) {
?>
<div class="notice notice-warning is-dismissible">
<p><?php echo "{$page_title} was not created! Check whether it already exists"; ?></p>
</div>
<?php
});
}
}
}
Let me know if you have any question.
Answer to the additional questions
Yes it's feasible to do so. Wordpress keeps track of the blog posts page under page_for_posts option. It also store the info for front page under page_on_front and show_on_front options. So to assign your pages to the blog and front pages, you'll update those options.
So when the custom function fires off in the after_switch_theme action hook, after the foreach loop you could add the following code to assign your pages:
$blog_page = get_page_by_title('news', 'OBJECT', 'page');
if ($blog_page) {
update_option('page_for_posts', $blog_page->ID);
}
$front_home_page = get_page_by_title('home', 'OBJECT', 'page');
if ($front_home_page) {
update_option('page_on_front', $front_home_page->ID);
update_option('show_on_front', 'page');
}
get_page_by_titleDocs
So the entire custom function for the after_switch_theme action hook would be something like this:
add_action('after_switch_theme', 'my_custom_pages_on_theme_activation');
function my_custom_pages_on_theme_activation()
{
$pages_array = array(
'products page' => '',
'policy page' => '',
'services page' => ''
);
foreach ($pages_array as $page_title => $page_content) {
$current_page = your_theme_create_page($page_title, $page_content);
if (false != $current_page) {
add_action('admin_notices', function () use ($page_title) {
?>
<div class="notice notice-success is-dismissible">
<p><?php echo "Done! {$page_title} has been created"; ?></p>
</div>
<?php
});
} else {
add_action('admin_notices', function () use ($page_title) {
?>
<div class="notice notice-warning is-dismissible">
<p><?php echo "{$page_title} was not created! Check whether it already exists"; ?></p>
</div>
<?php
});
}
}
$blog_page = get_page_by_title('news', 'OBJECT', 'page');
if ($blog_page) {
update_option('page_for_posts', $blog_page->ID);
}
$front_home_page = get_page_by_title('home', 'OBJECT', 'page');
if ($front_home_page) {
update_option('page_on_front', $front_home_page->ID);
update_option('show_on_front', 'page');
}
}

Wordpress - How to get the information of a widget instance

I wanted to know how to get the information of a widget instance, to be able to get all its information from another widget. Try the Get Widget ID plugin but it returns "temp" as a result and I also tried with this code block:
https://wordpress.stackexchange.com/questions/240327/how-to-access-widget-data-from-outside-widget
But I still get the same result.
My idea is the following:
I am modifying a Wordpress widget so that it selects a static post in order to fulfill the function of a featured post in a digital newspaper ... The widget has already been modified and is already working. That same widget is repeated in several places on my website, that is, I use it several times (each with a different selected post).
My idea is to show the featured posts with that widget (those selected by the editor) and modify another widget, that shows me all the posts except the ones that are selected in those widgets. For that I want to know how to get the instance of said widgets that select the featured post, to be able to get the ID of the selected post in each widget and show all the posts except those that are already as featured posts.
In summary ... I just want to see no news that is selected as featured again.
Clarification: This is not a widget written by me, it is a template that I bought and since it did not have this functionality, I am trying to create it.
I leave the code of my widget, in case it is of any use:
<?php
if ( ! defined( 'ABSPATH' ) ) exit;
add_action('widgets_init', 'seleccion_subtitulo');
function seleccion_subtitulo() {
register_widget('seleccion_subtitulo');
}
class seleccion_subtitulo extends WP_Widget {
/*-----------------------------------------------------------------------------------*/
/* Widget Setup
/*-----------------------------------------------------------------------------------*/
public function __construct() {
$widget_ops = array(
'classname' => 'seleccion_subtitulo',
'description' => esc_html__('Seleccionar noticia con titulo y subtitulo', 'disto')
);
parent::__construct('seleccion_subtitulo', esc_html__('Noticias: Noticia titulo + subtitulo [Estilo 1]', 'disto'), $widget_ops);
}
/*-----------------------------------------------------------------------------------*/
/* Display Widget
/*-----------------------------------------------------------------------------------*/
function widget($args, $instance) {
extract($args);
$featured_post = isset($instance["featured_post"]) ? $instance["featured_post"] : '';
$posts = null;
$args = array(
'p' => $featured_post,
'posts_per_page' => 1,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'ignore_sticky_posts' => true
);
$posts_query = new WP_Query;
$posts = $posts_query->query($args);
$unique_block_id = rand(10000, 900000);
echo '<div class="jl_large_builder jl_nonav_margin jelly_homepage_builder jl-post-block-'.esc_html($unique_block_id).'">';
if (!empty($instance['titles'])) {?>
<div class="homepage_builder_title">
<h2 class="builder_title_home_page">
<?php echo esc_attr($instance["titles"]);?>
</h2>
</div>
<?php }?>
<?php
while ($posts_query->have_posts()) {
$post_id = get_the_ID();
$posts_query->the_post();
$categories = get_the_category(get_the_ID());
?>
<div class="jl_post_title_top jl_large_format">
<h3 class="image-post-title"><a href="<?php the_permalink(); ?>">
<?php the_title()?></a></h3>
</div>
<div class="post-entry-content">
<div class="post-entry-content-wrapper">
<div class="large_post_content">
<p>
<?php echo wp_trim_words( get_the_content(), 34, '...' );?>
</p>
<!-- <div class="jl_large_sw">
<?php echo esc_html__('Read More', 'disto')?>
<?php if(function_exists('disto_share_footer_link')){echo disto_share_footer_link(get_the_ID());}?>
</div> -->
</div>
</div>
</div>
<div class="box jl_grid_layout1 blog_large_post_style">
<?php if ( has_post_thumbnail()) {?>
<div class="jl_front_l_w">
<?php $slider_large_thumb_id = get_post_thumbnail_id();
$slider_large_image_header = wp_get_attachment_image_src( $slider_large_thumb_id, 'disto_slider_grid_large', true ); ?>
<?php if($slider_large_thumb_id){?>
<span class="image_grid_header_absolute" style="background-image: url('<?php echo esc_url($slider_large_image_header[0]); ?>')"></span>
<?php }else{?>
<span class="image_grid_header_absolute"></span>
<?php }?>
<?php if(get_theme_mod('disable_post_category') !=1){
$categories = get_the_category(get_the_ID());
if ($categories) {
echo '<span class="meta-category-small">';
foreach( $categories as $tag) {
$tag_link = get_category_link($tag->term_id);
$title_bg_Color = get_term_meta($tag->term_id, "category_color_options", true);
$title_reactions = get_term_meta($tag->term_id, "disto_cat_reactions", true);
if($title_reactions){}else{echo '<a class="post-category-color-text" style="background:'.$title_bg_Color.'" href="'.esc_url($tag_link).'">'.$tag->name.'</a>';}
}echo "</span>";}}?>
<?php echo disto_post_type();?>
</div>
<?php }?>
<div class="jl_post_title_top jl_large_format">
<?php echo disto_single_post_meta(get_the_ID()); ?>
</div>
</div>
<?php }
if($post_loadmore == 1){echo '<div class="jl-loadmore-btn-w">'.esc_html__('Load more', 'disto').'</div>';
wp_add_inline_script( 'disto-custom', "(function($){ $(document).ready(function() {'use strict'; var current_page_".esc_js($unique_block_id)." = 1; $('.jl-post-block-".esc_js($unique_block_id)." .jl_btn_load').click(function(e){ e.preventDefault(); e.stopPropagation(); var button = $(this), data = {'action': 'jl_post_more','query': ".json_encode( $posts_query->query_vars , true).",'page' : current_page_".esc_js($unique_block_id).",'cat' : '".esc_js($cats)."','jl_layout' : 'postslarge'}; var button_default_text = button.text(); $.ajax({ url : '".esc_url(site_url())."/wp-admin/admin-ajax.php', data : data, type : 'POST', beforeSend : function ( xhr ) {button.text('');button.addClass('btn-loading'); }, success : function( data ){ if( data ) { button.text( button_default_text ); button.removeClass('btn-loading'); $('.jl-post-block-".esc_js($unique_block_id)." .jl-loadmore-btn-w').before(data); current_page_".esc_js($unique_block_id)."++; if ( current_page_".esc_js($unique_block_id)." == ".esc_js($posts_query->max_num_pages)." ) button.remove(); }else {button.remove();}}});});});})(jQuery);");
}
wp_reset_postdata();
?>
</div>
<?php }
/*-----------------------------------------------------------------------------------*/
/* Update Widget
/*-----------------------------------------------------------------------------------*/
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['featured_post'] = $new_instance['featured_post'];
return $instance;
}
/*-----------------------------------------------------------------------------------*/
/* Widget Settings (Displays the widget settings controls on the widget panel)
/*-----------------------------------------------------------------------------------*/
function form( $instance ) {?>
<h2>Elige una de las ultimas 20 noticias para establecerla como portada secundaria.</h2>
<div class="container">
<p>
<label>
<strong> <?php esc_html_e('Seleccionar noticia destacada:', 'disto');?></strong>
</label>
</p>
<p>
<select id="<?php echo esc_attr( $this->get_field_id( 'featured_post' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'featured_post' ) ); ?>">
<?php
$posts_args = array('posts_per_page' => 20,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'ignore_sticky_posts' => true);
$last_entries = get_posts($posts_args);
foreach ($last_entries as $entry) {
?>
<option value="<?php echo $entry->ID; ?>" <?php if($instance['featured_post']==$entry->ID){ echo 'selected="selected"'; } ?> ><?php echo $entry->post_title; ?></option>
<?php
}
?>
</select>
</p>
</div>
<?php
}
}
?>
If I do var_dump ($instance) it shows me the following:
array(3) { ["featured_post"]=> string(4) "2970" ["so_sidebar_emulator_id"]=> string(29) "seleccion_subtitulo-421210000" ["option_name"]=> string(26) "widget_seleccion_subtitulo" }
I estimate that the following value tells me the ID of my widget instance:
["so_sidebar_emulator_id"] => string (29) "seleccion_subtitulo-421210000"
but I don't know how to invoke it from another widget, to get the information from it.
When obtaining that information, I try the following code to see what I get (I saw this code in the link that happens first):
$widget_name = 'seleccion_subtitulo';
$widget_instance = '421210000';
$widget_instances = get_option('widget_' . $widget_name);
$data = $widget_instances[$widget_instance];
var_dump($widget_instances);
If I do var_dump($data); I get NULL
If I do var_dump($widget_instances); I get:
array(1) { ["_multiwidget"]=> int(1) }
Lets rephrase your question into 2 parts:
"How to get a widgets settings"
"How to get the list of featured posts as used by that widget for purpose of excluding them from another list of posts"
1. Widget settings:
Widget settings are stored in the database in the wp_options table. If you do a search in phpmyadmin using widget% wildcard in the option name field you will see all widgets and their serialised data arrays.
You may note that they all have a subarray called "_multiwidget" which will contain the instances and their settings. In your example above you dumped this ["_multiwidget"]=> int(1)
This shows that nothing has yet been stored for that widget. The widget is not in a sidebar and/or no featured posts have been defined for that widget.
If the widget had been saved to a sidebar with some settings we would be seeing more details here.
Setup some widget instances so you can see the saved data structures. Then you will be able to see the widget details (either via phpmyadmin or by dumping as before)
2. Get list of featured posts out of a set of widget instances in order to exclude them from a query (in another widget)
For the widget you looking at we would probably see an array of settings one of which would be called "featured_post".
Once the widget has been dragged to some sidebars and has some featured posts defined in a few instances, you can then in your new widget do something like (pseudo code):
$widget_name = 'seleccion_subtitulo'; //if that's the widget name in the db.
$widget_settings = get_option('widget_' . $widget_name);
$featured_posts = array();
if (!empty($widget_settings)) {
if (!empty($widget_settings["_multiwidget"])) {
$instances = $widget_settings["_multiwidget"];
foreach ( $instances as $wid => $instance) {
$featured_posts[] = $instance['featured_post']; // if that is how it is stored in the widget details
}
}
}
You can then use https://developer.wordpress.org/reference/functions/get_posts/ and pass the array $featured_posts
in the argument array as
'exclude' => $featured_posts
Note that It is not necessary to know the 'instance' or the 'widget id' for what you say to want to achieve, one simply has to loop through all the instances for that widget.

Shortcode not working over index.php only

I have download some plug-in to render youtube search inside my site, the shortcode working perfect at pages/posts but when I use <?php echo do_shortcode('[soundcloud_wpress]');?> over my index.php, it's doesn't show anything.
index.php:
<?php
/**
* The main template file
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* e.g., it puts together the home page when no home.php file exists.
*
* Learn more: {#link https://codex.wordpress.org/Template_Hierarchy}
*
* #package WordPress
* #subpackage Twenty_Fifteen
* #since Twenty Fifteen 1.0
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<div class="row searchdiv-wrapper">
<div class="col-sm-6 youtube-search">
<?php echo do_shortcode('[youtube_wpress]');?>
</div>
<div class="col-sm-6 soundcloud-search">
<?php echo do_shortcode('[soundcloud_wpress]');?>
</div>
</div>
</main><!-- .site-main -->
</div><!-- .content-area -->
<?php get_footer(); ?>
The plugin add shortcode:
$GLOBALS['ygp_youtube_wpress'] = get_option('ygp_youtube_wpress');
$GLOBALS['ygp_youtube_wpress']['plugin_code'] = 'youtube_wpress';
$GLOBALS['ygp_youtube_wpress']['item_name'] = 'youtube_wpress';
//error_reporting(E_WARNING);
require_once dirname( __FILE__ ).'/include/vbox/include/webzone.php';
require_once dirname( __FILE__ ).'/activation.php';
$a1=new Youtube_wpress_activation();
if($a1->verify_activation()) {
require_once dirname( __FILE__ ).'/youtube_widget.php';
}
if(is_admin()) {
require_once dirname( __FILE__ ).'/admin/options.php';
}
class Youtube_wpress {
function Youtube_wpress() {
if(is_admin()) {
register_activation_hook(__FILE__, array(__CLASS__, 'on_plugin_activation'));
//Settings link
add_filter( 'plugin_action_links', array(__CLASS__, 'plugin_action_links'), 10, 2);
}
//Shortcodes
add_shortcode('youtube_wpress', array(__CLASS__, 'youtube_wpress_shortcode'));
}
function add_scripts_wp_footer() {
}
I have added only the first top code from the plug-in class .
Any idea why echo shortcode not working only inside index.php ?
Thanks and sorry for beginner questions.
Here are some notes on how you should use the do_shortcode() function:
<?php
add_filter( 'the_content', 'do_shortcode', 11 ); // From shortcodes.php
// Use shortcode in a PHP file (outside the post editor).
echo do_shortcode( '' );
// In case there is opening and closing shortcode.
echo do_shortcode( '[iscorrect]' . $text_to_be_wrapped_in_shortcode . '[/iscorrect]' );
// Enable the use of shortcodes in text widgets.
add_filter( 'widget_text', 'do_shortcode' );
// Use shortcodes in form like Landing Page Template.
echo do_shortcode( '[contact-form-7 id="91" title="quote"]' );
// Store the short code in a variable.
$var = do_shortcode( '' );
echo $var;
?>
There is an exception to the built-in embed shortcode available with WordPress. In order to use this shortcode with do_shortcode(), you can do the following:
<?php
$embedurl = 'http://yourembeddableurl.com';
if ( ! empty( $embedurl ) ) {
$var = apply_filters( 'the_content', "" );
echo $var;
}
?>

Codeigniter creating dynamic sidebars

I was looking for a flexible way to generate different sidebars in different pages. The goal is to pass custom links to each sidebar. The template libraries seemed overkill for my application so I developed an easy solution. I'm not certain if it's the best solution. My question is what do you think? Your advice is immensely appreciated!
1. In your controller add a private function that loads your sidebar view:
/**
* The function has 2 arguments.
* $title is the sidebar widget title.
* $widget will contain an array of links to be added in the sidebar widget.
*/
private function sidebar($title, $widget)
{
$widget['title'] = $title;
$this->load->view('includes/sidebar', $widget);
}
2. In the controller functions that you want to load a custom sidebar, call the private function sidebar() and pass desired sidebar data into it.
Below is a controller function named edit used to edit posts. In the example I need to load a sidebar with options to view and delete the post I'm on:
function edit($post_id = '')
{
//your code, form validation, etc...
//Prepare sidebar widget links
//Array key is link url, array value is link name
$widget['links'] = array (
'posts/single/' . $post_id => 'View post',
'posts/remove/' . $post_id => 'Remove post'
);
$this->sidebar('Options', $widget); //load sidebar
}
3. Finally the sidebar view displaying custom data passed from the controller:
<div id="sidebar">
<ul>
<li class="widget">
<div class="label"><?php echo $title; ?></div>
<ul>
<?php foreach ($links as $link => $value): ?>
<li><?php echo anchor($link, $value); ?></li>
<?php endforeach; ?>
</ul>
</li>
</ul>
</div>
Conclusion
Add the following code to any controller function for custom sidebar title and links:
$widget['links'] = array (
'controller/function' => 'Link Name 1',
'controller/function' => 'Link Name 2',
'controller/function' => 'Link Name 3'
);
$this->sidebar('Widget Title', $widget);
I think that gets it done. I'm not an expert in CodeIgniter, but I can tell you that's just fine. One thing you should always make sure is to validate the data passed to a function. In this case:
private function sidebar($title=FALSE, $widget=FALSE) {
if ($title && $widget) {
//process
}
else
return FALSE
}
}
Another way to do it is just to pass the links to the template (not the sidebar template, but your main template:
$data['sidebar'] = array('link/link'=>'My Link');
$this->load->view('mytemplate', $data);
And in the template you load the sidebar template and pass it the data:
<html>
<!--All my html-->
<?php $this->load->view('includes/sidebar', $data['sidebar']); ?>
</html>
This is just another option. But what you did is just fine.

Categories