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.
Related
I'm creating my first wordpress plugin to show some dashboard data on the wp-admin-page, however only my php code is recognized when I edited my plugin, any html markup I write is omitted.
I want to make my plugin using HTML+bootstrap for the Front-end but make some calculations using PHP but I don't understand how I can do this.
In my first attempt, I could only echo html markup:
<?php
add_action( 'admin_menu', 'test_plugin_setup_menu' );
function test_plugin_setup_menu(){
add_menu_page( 'Page Title', 'Menu title', 'manage_options', 'test-plugin', 'test_init' );
}
function test_init(){
echo "<h1> Hello World! </h1>";
}
?>/*THIS OUTPUT ON MY WP ADMIN PAGE AS EXPECTED WITH A HELLO WORLD
However I need to write a lot of HTML markup with Bootstrap and only use PHP in some areas but any HTML code I write after my ?> doesn't get show on the page.
Second approach: I referred to my HTML file with PHP
<?php
add_action( 'admin_menu', 'test_plugin_setup_menu' );
function test_plugin_setup_menu(){
add_menu_page( 'Page Title', 'Menu title', 'manage_options', 'test-plugin', 'test_init' );
}
function test_init(){
$file = file_get_contents('index.html', FILE_USE_INCLUDE_PATH);
if($file == false)
{
echo 'file not found';
}
else
{
echo $file;
}
}
?>
This last attempt indeed shown all my HTML login with my bootstrap styled perfectly on the wp-admin-page but i cant use the PHP logic or DB connections I need on this HTML file..
My question is: how can I use my HTML markup in my PHP plugin simultaneously?
Extra info
I'm very new to PHP and Wordpress so I don't know what am I doing wrong in my code so HTML tags cant be show on the page unless I referred them to an external file.
Any help is greatly appreciated.
Another alternative would be to include your php file. Here's the idea:
add_action( 'admin_menu', 'test_plugin_setup_menu' );
function test_plugin_setup_menu() {
add_menu_page( 'Page Title', 'Menu title', 'manage_options', 'test-plugin', 'test_init' );
}
function test_init() {
ob_start();
include_once 'file-that-i-want-to-include.php';
echo ob_get_clean();
}
Then of course in your file-that-i-want-to-include.php. Just create your page like you normally do:
<?php
include_once 'mydatabaseconnction.php';
// ... and so on php codes of sorts
?>
<div class="container">
<div class="row">
<div class="col">
my contents whatever
</div>
</div>
</div>
In addition, you can just load bootstrap in that specific admin settings page if you'd like:
add_action('admin_enqueue_scripts', function() {
if (get_current_screen()->id === 'toplevel_page_test-plugin') { // the prefix is "toplevel_page_"
$css_path = plugins_url('assets/vendor/bootstrap/bootstrap.min.css'); // just change the path going to your css and js
$js_path = plugins_url('assets/vendor/bootstrap/bootstrap.min.js');
wp_enqueue_style('latest-bootstrap-css', $css_path, [], '4.5.0');
wp_enqueue_script('latest-bootstrap-js', $js_path, [], '4.5.0');
}
});
How to create a function in a custom page and use it in single.php?
I have the custom page mypage.php
<?php
/* Template Name: Form */
...
$myname = add_post_meta( $date, 'My Name', $name, true );
function name(){
if ($myname != ''){
echo ="Hello World! ";
}
}
get_header(); ?>
...
?>
Single page
<? php name(); ?>
To have functions available in all theme template files, you need to put them inside the file /wp-content/themes/your-theme/functions.php.
Just move your function to it, and call it in any template (single, page, archives, category). Check the documentation: Functions File Explained.
And to make the logic of your code work, you'd need to use get_post_meta in the function:
function name(){
$myname = get_post_meta('My Name');
if ($myname != ''){
echo "Hello World! ";
}
}
PS: it's a bit strange that you're setting a post meta everytime the mypage.php template is loaded...
Insert HTML Input to a themes template file?
My question is this:
Currently with my code, I can have whatever I've set in my custom settings page appear on
the end of every post using, of course, a WordPress filter.
The only thing is, I don't want what I input to go anywhere within a post. What I am trying to
achieve, is to have my input injected into the current themes home.php template file, within a <div></div> tag that's contained within that template file. The <div> in question has an ID attached, which is <div id="category-inner">, so is there any way use it's ID to target it in my plugin?
I've successfully managed to do it, by editing the actual home.php template file and inserting a bit of php directly there to show the user input, but that totally goes against what I'm trying to do, which is to not have to edit the source code of the template file and only have to use my plugin to insert the users inputted text in that specific location (the <div> mentioned above).
My plugin is only ever going to be adding user input in one place on the site, and it will never change. And the place it will always go in, is where I mentioned above.
Below is my plugin code:
<?php
/*/
Plugin Name: Custom Text Adder
Plugin URI: N/A
Description: Demonstrates how rubbish I am at pretty much everything I want to do
Version: 101
Author: JD
Author URI: N/A
/*/
// insert custom plugin settings menu
add_action('admin_menu', 'custom_create_menu');
add_filter('the_content', 'customhead_the_content');
function customhead_the_content($content) {
$output = $content;
$output .= '<div id="category-inner">';
$output .= get_option('post_text');
$output .= '</div>';
return $output;
}
// Add Font-Size to WYSIWYG Editor
function wp_editor_fontsize_filter( $options ) {
array_shift( $options );
array_unshift( $options, 'fontsizeselect');
array_unshift( $options, 'formatselect');
return $options;
}
add_filter('mce_buttons_2', 'wp_editor_fontsize_filter');
// Create Custom Menu
function custom_create_menu() {
//create new top-level menu
add_menu_page('Custom Plugin Settings', 'Custom Settings', 'administrator', __FILE__, 'custom_settings_page',plugins_url('/img/icon.png', __FILE__));
//call register settings function
add_action( 'admin_init', 'register_mysettings' );
}
// Register our settings
function register_mysettings() {
register_setting( 'custom-settings-group', 'new_option_name' );
register_setting( 'custom-settings-group', 'some_other_option' );
register_setting( 'custom-settings-group', 'option_etc' );
register_setting( 'custom-settings-group', 'font_size' );
register_setting( 'custom-settings-group', 'post_text' );
}
function custom_settings_page() {
?>
<!-- Custom Settings Page Container -->
<div class="wrap">
<h2>Custom Text</h2>
<form method="post" action="options.php">
<?php settings_fields( 'custom-settings-group' ); ?>
<table class="form-table">
<?php /* Bring the editor onto the page */
wp_editor( '', 'post_text', $settings = array() );
// 4.
// Custom buttons for the editor.
// This is a list separated with a comma after each feature
// eg. link, unlink, bold, ...
$settings = array(
'textarea_name' => 'post_text',
'media_buttons' => true,
'tinymce' => array(
'theme_advanced_buttons1' => 'formatselect,|,bold,italic,underline,|,' .
'bullist,blockquote,|,justifyleft,justifycenter' .
',justifyright,justifyfull,|,link,unlink,|' .
',spellchecker,wp_fullscreen,wp_adv'
)
);
submit_button( 'Save everything', 'primary', 'submit' ); ?>
</table>
</form>
</div>
<?php }; ?>
Here is the screenshot which will be able to explain this in the most concise way possible:
http://i.imgur.com/hiEjEsA.jpg
Again, any and all help is hugely appreciated and will hopefully stop my brain from hurting!
You all rock,
Casey. :)
I'm not sure if you want this to be a pure PHP solution, but since you have the ID of the div you could target it with jQuery and insert the text into the div on page load (or form submit) with something like this:
$(document).ready(function() {
var userText = $('#input-id').val();
$('#category-inner').html(userText);
})
I think my previous question was over complicated and, to be honest, was confusing me, nevermind the people trying to answer.
I currently have to pages, both with one category of posts assigned to them, however both post pages are using the same content.php and content-single.php, but i was both pages to use different iterations of these pages for cosmetic reasons.
As an example, visit http://dev.n8geeks.com/blog/ and click on the first blog post. It displays a thumbnail, which is cool and is what i want. However, now on the "videos" page as seen here; http://dev.n8geeks.com/videos/ (once there, click on the post) it also shows the thumbnail box (but no thumbnails will be attached on this posts page category).
This is why i need to user different iterations of content.php and content-single.php, but i simply don't know how. It would also be great if the "videos" page had the same formatting as the "blog" page, but again, i don't know how to achieve this.
The code i'm using for the current "videos" page is as below.
<?php get_header(); ?>
<div id="content">
<div id="main">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; else: endif; ?>
<?php query_posts('category_name='.get_the_title().'&post_status=publish,future');?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h1 class="entry-title"><a href="<?php the_permalink(); ?>">
<?php the_title(); ?></a></h1>
<p><?php the_content(); ?>
<?php endwhile; else: endif; ?>
</div>
</div>
<?php get_footer(); ?>
Thanks in advance, i really appreciate any help like you wouldn't believe - it's 4:33am and i'm going insane trying to find a fix for this.
Regards
Still extremely confusing, haha, but from the sounds of it you want different templates to show up based on which category the post is in when you're viewing a single post?
If so, you could try setting this as you single.php:
<?php get_header(); ?>
<?php
if ( have_posts() ) { the_post(); rewind_posts(); }
if ( in_category(1) || in_category(2) ) {
include(TEMPLATEPATH . '/single-cat1-2.php');
}
else {
include(TEMPLATEPATH . '/single-default.php');
}
?>
<?php get_footer(); ?>
(from http://wordpress.org/support/topic/alternate-single-post-template-for-specific-categories)
And create the files 'single-cat1-2.php' and 'single-default.php', just add to the if statement checking to see if the post is in a certain category (or categories) and load the correct template. You can use ID, name, and their slug as selectors for the in_category function as well, read more here.
EDIT:
Kay, well you do need to learn plugin programming to really do this. I've begun a quick plugin for you to help you out. It works, just isn't perfect. You could definitely use a different system, like tying the categories in the category menu, but I didn't feel like playing with the Settings API for that page.
So make a new directory in your plugins directory, call it PostCatTheme, make a new file in there called index.php and put this in it:
<?php
/*
* Plugin Name: Post Category Templates
*/
//Replace __FILE__ with whatever the real path is because of symbolic link
/**
* Allows declarations of which categories a single-post template is assigned to
*/
class WordpressPostCatTheme
{
private $pluginDir, $templates;
function __construct ()
{
$this->pluginDir = dirname(__FILE__);
add_action("init", array($this, "load"));
add_filter('single_template', array($this, 'get_post_template'));
}
public function WPCT_deactivate ()
{
delete_option("PostCatTheme_templates");
}
public function load ()
{
register_deactivation_hook( __FILE__, array(&$this, 'WPCT_deactivate') );
$this->templates = get_option("PostCatTheme_templates");
if ($this->templates === FALSE)
{
$this->templates = $this->get_post_templates();
update_option("PostCatTheme_templates", $this->templates);
}
}
// This function scans the template files of the active theme,
// and returns an array of [category] => {file}.php]
public function get_post_templates()
{
$themes = get_themes();
$theme = get_current_theme();
$templates = $themes[$theme]['Template Files'];
$post_templates = array();
$base = array(trailingslashit(get_template_directory()), trailingslashit(get_stylesheet_directory()));
foreach ((array)$templates as $template)
{
$template = WP_CONTENT_DIR . str_replace(WP_CONTENT_DIR, '', $template);
$basename = str_replace($base, '', $template);
// don't allow template files in subdirectories
if (false !== strpos($basename, '/'))
continue;
$template_data = implode('', file( $template ));
$categories = '';
if (preg_match( '|Categories (.*)$|mi', $template_data, $categories))
$categories = _cleanup_header_comment($categories[1]);
//The categories are split by a | (pipe), if there aren't any pipes, assume it's just
//one category, otherwise split at the pipe
if (empty($categories))
continue;
if (strpos($categories, "|") === FALSE)
$categories = array($categories);
else
$categories = explode("|", $categories);
foreach ($categories as $category)
{
if (!empty($category))
{
if (isset($post_templates[$category]))
throw new Exception("Error, category assigned to more than one template");
if(basename($template) != basename(__FILE__))
$post_templates[trim($category)] = $basename;
}
}
}
//file_put_contents($this->pluginDir . "/log", json_encode($post_templates));
return $post_templates;
}
// Filter the single template value, and replace it with
// the template chosen by the user, if they chose one.
function get_post_template($template)
{
global $post;
$cats = wp_get_post_categories($post->ID);
//Go through each category, until one hits
foreach ($cats as $c)
{
$templateP = $this->templates[$c];
if(!empty($templateP) && file_exists(TEMPLATEPATH . "/{$templateP}"))
{
$template = TEMPLATEPATH . "/{$templateP}";
break;
}
}
return $template;
}
}
if (!isset($PostCatThemePlugin))
$PostCatThemePlugin = new WordpressPostCatTheme;
?>
After that, in your custom single.php template, add the code Categories: 1|2 in the header section (where Template Name is). Whenever you change or add these, make sure to deactivate and reactivate the plugin, to refresh the cache that this information is stored in.
To get the ID of a category, edit a category and in the URL, the number after tag_ID= is the category's ID.
Hope that helps some,
Max
I want to change the class names of the sidebar widgets on every different category page of WordPress and I figured the best way to do this would be to make a function in functions.php with all the conditions and return the required class name. I then called the function in the list tags of the register_sidebar function.
if (function_exists('register_sidebar')) {
register_sidebar(array(
'before_widget' => '<li class="sidebarModule">',
'after_widget' => '</li><!-- end module -->',
'before_title' => '<h2 class="moduleTitle "'.set_widget_title_color().'>',
'after_title' => '</h2>',
));
}
function set_widget_title_color() {
if(is_category('technology')) {
$color = "catNavColor1_active";
} elseif(is_category('gadgets')) {
$color = "catNavColor2_active";
} elseif(is_category('social-media')) {
$color = "catNavColor3_active";
} elseif(is_category('gaming')) {
$color = "catNavColor4_active";
} elseif(is_category('other')) {
$color = "catNavColor5_active";
}
return $color;
}
For some reason the above doesn't work. Please Help
Thanks
I think register_sidebars is called too early in the process, when the category is not defined yet. Have you tried implementing the dynamic_sidebar_params filter? I could not find anything in the WordPress Codex, but I found this nice example. Your other question on this topic also has a complete answer.
This only works if you implement the sidebars using dynamic_sidebar in your widget, as this function calls the dynamic_sidebar_params filter. If you have static widgets (defined in your template, not using the widget admin page), you should add a call to your function in that template code, like this:
<li class="sidebarModule">
<h2 class="moduleTitle <?php echo set_widget_title_color(); ?>">Widget title</h2>
<?php /* Your widget code */ ?>
</li><!-- end module -->