question
stringlengths 0
34.8k
| answer
stringlengths 0
28.3k
| title
stringlengths 7
150
| forum_tag
stringclasses 12
values |
---|---|---|---|
I know how to hardcode that... but i like to have a plugin with shortcode that will make it for me... do you know any... If not, i will have to make it myself Have a page (blank) and build it base on post category. So in page xyz display all the post with category=abc. So the build page will display all the abc post back to back. Framework do that, but i only have a simple theme... how to do that ? And yes, i know that clicking on category will just do that, but it's less managable !
|
I dont quite understand how it's less easier to manage a category... So you have <code> Category -> Post </code> but instead you want <code> Page -> Category -> Post </code> It doesn't make sense in what you are trying to do. And and if your trying to link categories into pages just so you can include them in some form of navigation, WP3.0+ has the ability to link categories with <code> Appearance -> Menus </code> . And you don't really manage a category you just manage the posts associated to a category.
|
Build page base on category
|
wordpress
|
Is it possible to retreive media image directly into the library... Something like get_media ('all') and it return a array with image url, caption, description etc etc..
|
Here you go: <code> function get_media_all_wpa14177(){ $args = array( 'post_type' => 'attachment', 'post_mime_type' =>'image', 'post_status' => 'inherit', 'posts_per_page' => -1, ); $query_images = new WP_Query( $args ); $images = array(); foreach ( $query_images->posts as $image) { $images[]= $image->guid; } return $images; } </code> Usage: <code> $Images = get_media_all_wpa14177(); </code>
|
Function to get image from media library
|
wordpress
|
Is there a browser plugin or method to find which php template an item is coming from?
|
The Debug Bar together with the Debug-Bar-Extender will show you what template file is being used.
|
Is there a browser plugin or method to find which php template an item is coming from?
|
wordpress
|
I'd like to be able to show sticky posts at the top of category pages. I'm using archive.php for my category page. I'm using the code below to display sticky posts at the top of my category archive page followed by the rest of the posts within that category. This works fine, until there are no sticky posts to display within the category and then it duplicates the posts list. <code> <?php // get the current category $category = get_the_category(); // get the sticky post in the category, order by title - ascending query_posts(array( 'post__in' => get_option('sticky_posts'), 'orderby' => 'title', 'post_date' => 'DESC' , 'cat' => ''.$category[0]->cat_ID.'' )); ?> <?php if (have_posts()) : ?> <?php if ($cat) {echo "<h2>Articles in " . get_the_category_by_ID($cat) . "</h2>";} ?> <ul id="archive-list"> <?php while (have_posts()) : the_post(); ?> <li class="sticky"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <span>Updated on <?php the_modified_date(); ?> at <?php the_modified_time() ?></span></li> <?php endwhile; ?> </ul> <?php endif; ?> <?php // get the sticky post in the category, order by title - ascending query_posts(array( 'post__not_in' => get_option('sticky_posts'), 'orderby' => 'title', 'post_date' => 'DESC' , 'cat' => ''.$category[0]->cat_ID.'' ) ); ?> <?php if (have_posts()) : ?> <ul id="archive-list"> <?php while (have_posts()) : the_post(); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <span>Updated on <?php the_modified_date(); ?> at <?php the_modified_time() ?></span></li> <?php endwhile; ?> </ul> <?php if(function_exists('wp_page_numbers')) { wp_page_numbers(); } ?> <?php else : ?> <h1 class="center">Sorry, no articles have been published in the <?php if ($cat) {echo "" . get_the_category_by_ID($cat) . "";} ?> category.</h1> <?php include (TEMPLATEPATH . '/searchform.php'); ?> <?php endif; ?> </code> Any help would be greatly appreciated! Thanks.
|
try to use a conditional statement to wrap the first loop, such as: <code> if( get_option('sticky_posts') ) : //only do the next part if sticky posts </code> add the corresponding <code> endif; </code> after the <code> endif; </code> of the first loop.
|
Show Sticky Posts in Category Archive
|
wordpress
|
I am trying to save my meta box, I have something like <code> function xxx_meta_box_callback() { add_meta_box('xxx-meta', 'xxx Details', 'xxx_meta_box', 'xxx-post-type', 'side', 'default'); add_action('save_post', 'xxx_save_meta_box'); error_log('meta box cb'); } function xxx_save_meta_box($post_id, $post) { error_log('running ...'); die('OK!!!'); } </code> I am getting "meta box cb" ok in my error log, but <code> xxx_save_meta_box() </code> does not seem to run. Why is that?
|
Hi @JM at Work: Try this in your theme's <code> functions.php </code> file, or a <code> .php </code> file of a plugin that you may be writing: <code> add_action('init', 'xxx_init'); function xxx_init() { add_action('save_post', 'xxx_save_meta_box'); } function xxx_meta_box_callback() { add_meta_box('xxx-meta','xxx Details','xxx_meta_box','xxx-post-type','side','default'); error_log('meta box cb'); } function xxx_save_meta_box($post_id, $post) { error_log('running ...'); die('OK!!!'); } </code>
|
Why is save_post hook not running?
|
wordpress
|
Conditionally Including scripts whether js or css in xhtml document head...has been a generally tricky affair, especially if you want to enqueue something, based on a shortcode or custom meta field or a widget. If you know that you need your script for sure,you would just do what the Wordpress Codex suggest by using wp_enqueue_script with following hooks, <code> * init * template_redirect * admin_print_scripts </code> But sometimes you require a more nuance inclusion of a script or stylesheet. Script inclusions based on shortcodes for example. The issue with shortcodes is that you couldn't really tell if a shortcode has been used, unless you apply strpos() on the content. The reason for this is because, the 'init' + 'template_redirect' + 'admin_print_scripts' hooks fire before the WP_Query object is set, i believe. So it can get tricky for conditionally including scripts for shortcodes and other triggers. To circumvent this, you can use strpos() with 'the_posts' hook, which gets fired before wp_head. But one of the drawbacks is that its an extra pass at the data. Discussed at http://beerpla.net/2010/01/13/wordpress-plugin-development-how-to-include-css-and-javascript-conditionally-and-only-when-needed-by-the-posts/ Additionally, i havn't seen examples of this enqueue scripts with this hook being able inject js or css in the head of the document Scribu suggest, using a flag variable, and sending it to the footer, http://scribu.net/wordpress/optimal-script-loading.html ...but that's not feasible for css style sheets that should be included in the head portion of the document I've been pondering the best compromise,and wanted to know your thoughts. basically, my hook of choice is wp_head, because i have access to the WP_Query object, in case i need to search for the shortcode, or use a conditional tag, or even widget usage detection. If i know that i need to inject css or js, then i can just recall the wp_print_scripts() function, after figuring out if the page needs my js or css. Here is a framework for script inclusion on WP 3.1...i've used it successfully for js inclusion. Havn't tried it for CSS yet, but i suspect it will work the same. <code> add_action("wp_head","add_conditional_scripts", 20); function add_conditional_scripts() { global $posts, $wp_scripts; foreach ($posts as $post) { if ( condition_gets_met == true ) : wp_enqueue_script( "scripthandle" , get_home_url().'/js/scriptfilename.js, array('jcycle'), '1.0', true); // This will add to the $wp_scripts variable endif; } wp_print_scripts(); // This uses the $wp_script object, will print, out the newly enqueue script } </code> Note that the *condition_gets_met is a stand in for strpos check or a conditional tag, or custom_meta_field check. Any feed back or criticisms of doing it this way would be great.
|
To circumvent this, you can use <code> strpos() </code> with <code> the_posts </code> hook, which gets fired before wp_head. But one of the drawbacks is that its an extra pass at the data. You're essentially doing the same inside the callback you're hooking onto <code> wp_head </code> , i don't see the difference.. (please clarify if you think otherwise).. Whether you hook onto <code> the_posts </code> or <code> wp_head </code> you're still iterating over the same array data, ie. <code> $posts </code> .. I personally don't see the issue with setting a flag inside the <code> the_posts </code> hook and if there's a concern that the hook may get called multiple times, simply check for the flag at the start of the callback and return if it's already set(ensuring only one iteration over that array). I'm actually using this approach in a plugin i'm waiting to release, and i also realised the method Scribu posted about doesn't really work when you're using CSS, which can't go in the foot. Scribu mentioned possibly injecting CSS into the head with JS, but i personally find that somewhat hacky(my personal opinion). I have a function hooked onto <code> the_posts </code> which goes like this.. <code> public function on_the_posts( $posts ) { if( empty( $posts ) || $this->has_tabs ) return $posts; // trimmed code not relevant to the example foreach( $posts as $post ) { if( !stripos( $post->post_content, '[end_tabset]' ) ) continue; $this->has_tabs = true; } return $posts; } </code> How would this be any different inside a callback on <code> wp_head </code> , i'm still going to need to iterate over <code> $posts </code> aren't i? Is this a bad implementation of wp_enqueue_script for conditional usage? No, i don't think so personally.
|
Is this a bad implementation of wp_enqueue_script for conditional usage?
|
wordpress
|
I'm trying to test the comments template on a theme that is based on TwentyTen, using the the WP Theme Unit Test XML file, and there is one post that does not display comments properly. The post is called "Comment Test", and it contains 20 comments, including 2 pingbacks. The only thing that displays are the pingbacks. Is that the expected behavior? I can't seem to figure out why it's only displaying the pingbacks. Perhaps there is a setting I missed in the backend. The way to reproduce this, is to create a blog, apply the TwentyTen theme, and import the WP Theme Unit Test file: http://svn.automattic.com/wpcom-themes/demo/test-data.2011-01-17.xml Then visit the post called "Comment Test", published on March 3, 2008. You should see it say "20 Responses to Comment Test", and underneath it you should see 2 pingbacks, no comments. Thanks for you help, Dave
|
Twenty Ten has been tested by the theme review team and it passes all the unit tests. You can see how it looks on one of the demo test installs or another install I found . Try doing a fresh install of WordPress with a new database with no plugins.
|
WordPress TwentyTen Theme Incompatible with Theme Unit Test
|
wordpress
|
The script below creates a nav menu and assigns a page to it. Everything's working perfectly except that the nav menu is not being automatically assigned to my theme's "Header-menu" location. Any ideas why? <code> //Register menu locations for the theme add_action( 'init', 'register_my_menus' ); function register_my_menus() { register_nav_menus( array('header-menu' => __( 'Header Menu' ), 'footer-menu' => __( 'Footer Menu' )) ); } //Create a nav menu, add a page to it and assign it to the theme's "header-menu" location. $menu_id = wp_create_nav_menu( 'header-menu' ); $menu = array( 'menu-item-type' => 'custom', 'menu-item-url' => get_home_url('/'), 'menu-item-title' => 'Home', 'menu-item-status' => 'publish', 'theme_location' => 'header-menu', //Just a guess but didn't work!!! ); wp_update_nav_menu_item( $menu_id, 0, $menu ); </code>
|
<code> wp_create_nav_menu() </code> function accepts the menu name and not the menu location. and as for <code> wp_update_menu_item() </code> well its for items and not the menu itself. After digging in the code i found out that "assignment" of 'theme location' to a menu is not done using of the nav_menu API in WordPress but with theme options so: <code> //first get the current theme $theme = get_current_theme(); //get theme's mods $mods = get_option("mods_$theme"); //update mods with menu id at theme location $mods['nav_menu_locations']['header-menu'] = $menu_id; update_option("mods_$theme", $mods); </code> hope this helps :)
|
Custom nav menu is created with default pages, but not hooked to theme's custom menu location
|
wordpress
|
hey guys, <code> <?php urlencode(the_title()); ?> </code> doesn't take effect. this is my entrie line of code: <code> <li><a href="mailto:?subject=<?php urlencode(the_title()); ?>&amp;body=<?php the_permalink(); ?>">e-mail</a></li> </code> I don't want to have spaces in the_title(). Why does urlencode not work for me?
|
The <code> the_title() </code> echo the title. You must use <code> get_the_title() </code> instead. get_the_title() returns the title as string. Use <code> <? echo urlencode(get_the_title()) ?> </code>
|
urlencoding of the_title() doesn't work?
|
wordpress
|
When doing an automatic upgrade, I get this: Downloading update from http://wordpress.org/wordpress-3.1.1.zip … Unpacking the update… Could not create directory.: /public_html Installation Failed All my wp files are in /public_html and the directory already exists. The FTP user I am logging in as owns all the Wordpress files, so it cannot be a chmod problem. Is there any reason why this error is occurring?
|
I had this problem and the answer was found (a) in enabling ftp to write and (b) at least temporarily setting the directories to 777 although I think the latter permissions can be improved. I run vsftp with chroot'd users. After finding no mention in apache logs, setting the permissions to 777, changing ftp group to www-data, enabling anonymous ftp to write, tearing my hair out, kicking the dog etc etc the penny eventually dropped that ftp was not allowed to write. I also upgraded a multi-site to 3.1.1 and that needs 777 set (well probably less) but returns the files 640. It may be that a changed ftp configuration has tripped you up.
|
Upgrade to 3.1.1 Fails
|
wordpress
|
I've got a registered sidebar called "my-header" that affects the absolute positioning of elements below it in the markup. So I need to execute a query in header.php to determine if the sidebar is present for the current post, and write out a class identifier to my theme's body tag. I'll use this css class to adjust absolute positioning of elements accordingly. Is there a method that can be called, separately from the method that's used to display the sidebar, to determine if the post has widget content for the "my-sidebar" widget? For example, one that just returns true/false? After looking through widgets.php, I tried using is_active_sidebar('my-header') but it returns true for all pages. I need a function that accepts the post as an argument. Otherwise, if none exists, I suppose I'll create my own function.
|
<code> <?php $bodyclass = ""; // are we on a 'single' page? e.g. a post or page or some other custom post type? if(is_single()){ // is this a post of type 'page'? or is it a blogpost? global $post; if($post->post_type == 'page'){ // good now to check if we have a sidebar with active content if( is_active_sidebar('my-header')){ $bodyclass="wehavesidebarcontentyay"; } } } ?> <body <?php body_class($bodyclass); ?>> </code> Though I'm sure if you have body_class on your body tag then you already have the needed css classes and selectors to do this without the PHP code.
|
How to determine if post has widget content?
|
wordpress
|
OK, I have an issue with Sidebar Generator Plugin . This plugin creates subpage called "Sidebars" in WP-Admin. The point is, it is created as a child of "Appearance" page. And I don't want it here, I want "Sidebars" to be a subpage of my own Page named "my-page". I have found this line in the plugin's code: <code> function admin_menu(){ add_submenu_page('themes.php', 'Sidebars', 'Sidebars', 'manage_options', __FILE__, array('sidebar_generator','admin_page')); } </code> And changed 'themes.php' to 'my-page'. Now "Sidebars" is being displayed under My-Page, but when I try to access it it shows: You do not have sufficient permissions to access this page. Why does it happen and how to fix that? And additional question - the Sidebars subpage displays always at the top of my list of My-Page subpages, how to change that (in fact I want it to be the last subpage of My-Page). Original, full code: <code> <?php /* Plugin Name: Sidebar Generator Plugin URI: http://www.getson.info Description: This plugin generates as many sidebars as you need. Then allows you to place them on any page you wish. Version 1.1 now supports themes with multiple sidebars. Version: 1.1.0 Author: Kyle Getson Author URI: http://www.kylegetson.com Copyright (C) 2009 Kyle Robert Getson */ /* Copyright (C) 2009 Kyle Robert Getson, kylegetson.com and getson.info 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 3 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, see <http://www.gnu.org/licenses/>. */ class sidebar_generator { function sidebar_generator(){ add_action('init',array('sidebar_generator','init')); add_action('admin_menu',array('sidebar_generator','admin_menu')); add_action('admin_print_scripts', array('sidebar_generator','admin_print_scripts')); add_action('wp_ajax_add_sidebar', array('sidebar_generator','add_sidebar') ); add_action('wp_ajax_remove_sidebar', array('sidebar_generator','remove_sidebar') ); //edit posts/pages add_action('edit_form_advanced', array('sidebar_generator', 'edit_form')); add_action('edit_page_form', array('sidebar_generator', 'edit_form')); //save posts/pages add_action('edit_post', array('sidebar_generator', 'save_form')); add_action('publish_post', array('sidebar_generator', 'save_form')); add_action('save_post', array('sidebar_generator', 'save_form')); add_action('edit_page_form', array('sidebar_generator', 'save_form')); } function init(){ //go through each sidebar and register it $sidebars = sidebar_generator::get_sidebars(); if(is_array($sidebars)){ foreach($sidebars as $sidebar){ $sidebar_class = sidebar_generator::name_to_class($sidebar); register_sidebar(array( 'name'=>$sidebar, 'before_widget' => '<li id="%1$s" class="widget sbg_widget '.$sidebar_class.' %2$s">', 'after_widget' => '</li>', 'before_title' => '<h2 class="widgettitle sbg_title">', 'after_title' => '</h2>', )); } } } function admin_print_scripts(){ wp_print_scripts( array( 'sack' )); ?> <script> function add_sidebar( sidebar_name ) { var mysack = new sack("<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php" ); mysack.execute = 1; mysack.method = 'POST'; mysack.setVar( "action", "add_sidebar" ); mysack.setVar( "sidebar_name", sidebar_name ); mysack.encVar( "cookie", document.cookie, false ); mysack.onError = function() { alert('Ajax error. Cannot add sidebar' )}; mysack.runAJAX(); return true; } function remove_sidebar( sidebar_name,num ) { var mysack = new sack("<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php" ); mysack.execute = 1; mysack.method = 'POST'; mysack.setVar( "action", "remove_sidebar" ); mysack.setVar( "sidebar_name", sidebar_name ); mysack.setVar( "row_number", num ); mysack.encVar( "cookie", document.cookie, false ); mysack.onError = function() { alert('Ajax error. Cannot add sidebar' )}; mysack.runAJAX(); //alert('hi!:::'+sidebar_name); return true; } </script> <?php } function add_sidebar(){ $sidebars = sidebar_generator::get_sidebars(); $name = str_replace(array("\n","\r","\t"),'',$_POST['sidebar_name']); $id = sidebar_generator::name_to_class($name); if(isset($sidebars[$id])){ die("alert('Sidebar already exists, please use a different name.')"); } $sidebars[$id] = $name; sidebar_generator::update_sidebars($sidebars); $js = " var tbl = document.getElementById('sbg_table'); var lastRow = tbl.rows.length; // if there's no header row in the table, then iteration = lastRow + 1 var iteration = lastRow; var row = tbl.insertRow(lastRow); // left cell var cellLeft = row.insertCell(0); var textNode = document.createTextNode('$name'); cellLeft.appendChild(textNode); //middle cell var cellLeft = row.insertCell(1); var textNode = document.createTextNode('$id'); cellLeft.appendChild(textNode); //var cellLeft = row.insertCell(2); //var textNode = document.createTextNode('[<a href='javascript:void(0);' onclick='return remove_sidebar_link($name);'>Remove</a>]'); //cellLeft.appendChild(textNode) var cellLeft = row.insertCell(2); removeLink = document.createElement('a'); linkText = document.createTextNode('remove'); removeLink.setAttribute('onclick', 'remove_sidebar_link('$name')'); removeLink.setAttribute('href', 'javacript:void(0)'); removeLink.appendChild(linkText); cellLeft.appendChild(removeLink); "; die( "$js"); } function remove_sidebar(){ $sidebars = sidebar_generator::get_sidebars(); $name = str_replace(array("\n","\r","\t"),'',$_POST['sidebar_name']); $id = sidebar_generator::name_to_class($name); if(!isset($sidebars[$id])){ die("alert('Sidebar does not exist.')"); } $row_number = $_POST['row_number']; unset($sidebars[$id]); sidebar_generator::update_sidebars($sidebars); $js = " var tbl = document.getElementById('sbg_table'); tbl.deleteRow($row_number) "; die($js); } function admin_menu(){ add_submenu_page('themes.php', 'Sidebars', 'Sidebars', 'manage_options', __FILE__, array('sidebar_generator','admin_page')); } function admin_page(){ ?> <script> function remove_sidebar_link(name,num){ answer = confirm("Are you sure you want to remove " + name + "?\nThis will remove any widgets you have assigned to this sidebar."); if(answer){ //alert('AJAX REMOVE'); remove_sidebar(name,num); }else{ return false; } } function add_sidebar_link(){ var sidebar_name = prompt("Sidebar Name:",""); //alert(sidebar_name); add_sidebar(sidebar_name); } </script> <div class="wrap"> <h2>Sidebar Generator</h2> <p> The sidebar name is for your use only. It will not be visible to any of your visitors. A CSS class is assigned to each of your sidebar, use this styling to customize the sidebars. </p> <br /> <div class="add_sidebar"> <a href="javascript:void(0);" onclick="return add_sidebar_link()" title="Add a sidebar">+ Add Sidebar</a> </div> <br /> <table class="widefat page" id="sbg_table" style="width:600px;"> <tr> <th>Name</th> <th>CSS class</th> <th>Remove</th> </tr> <?php $sidebars = sidebar_generator::get_sidebars(); //$sidebars = array('bob','john','mike','asdf'); if(is_array($sidebars) && !empty($sidebars)){ $cnt=0; foreach($sidebars as $sidebar){ $alt = ($cnt%2 == 0 ? 'alternate' : ''); ?> <tr class="<?php echo $alt?>"> <td><?php echo $sidebar; ?></td> <td><?php echo sidebar_generator::name_to_class($sidebar); ?></td> <td><a href="javascript:void(0);" onclick="return remove_sidebar_link('<?php echo $sidebar; ?>',<?php echo $cnt+1; ?>);" title="Remove this sidebar">remove</a></td> </tr> <?php $cnt++; } }else{ ?> <tr> <td colspan="3">No Sidebars defined</td> </tr> <?php } ?> </table> <br /><br /> <div class="donate"> <h5>Donate</h5> <p> Support the further development of this plugin. </p> <form action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_s-xclick"> <input type="hidden" name="hosted_button_id" value="9271055"> <input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!"> <img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1"> </form> </div> </div> <?php } /** * for saving the pages/post */ function save_form($post_id){ $is_saving = $_POST['sbg_edit']; if(!empty($is_saving)){ delete_post_meta($post_id, 'sbg_selected_sidebar'); delete_post_meta($post_id, 'sbg_selected_sidebar_replacement'); add_post_meta($post_id, 'sbg_selected_sidebar', $_POST['sidebar_generator']); add_post_meta($post_id, 'sbg_selected_sidebar_replacement', $_POST['sidebar_generator_replacement']); } } function edit_form(){ global $post; $post_id = $post; if (is_object($post_id)) { $post_id = $post_id->ID; } $selected_sidebar = get_post_meta($post_id, 'sbg_selected_sidebar', true); if(!is_array($selected_sidebar)){ $tmp = $selected_sidebar; $selected_sidebar = array(); $selected_sidebar[0] = $tmp; } $selected_sidebar_replacement = get_post_meta($post_id, 'sbg_selected_sidebar_replacement', true); if(!is_array($selected_sidebar_replacement)){ $tmp = $selected_sidebar_replacement; $selected_sidebar_replacement = array(); $selected_sidebar_replacement[0] = $tmp; } ?> <div id='sbg-sortables' class='meta-box-sortables'> <div id="sbg_box" class="postbox " > <div class="handlediv" title="Click to toggle"><br /></div><h3 class='hndle'><span>Sidebars</span></h3> <div class="inside"> <div class="sbg_container"> <input name="sbg_edit" type="hidden" value="sbg_edit" /> <p> Select the sidebar you wish to display on this page, and which sidebar it will replace. (leave unselected to use the default sidebar everywhere) </p> <ul> <?php global $wp_registered_sidebars; //var_dump($wp_registered_sidebars); for($i=0;$i<5;$i++){ ?> <li>Replace <select name="sidebar_generator[<?=$i?>]"> <option value="0"<?php if($selected_sidebar[$i] == ''){ echo " selected";} ?>>WP Default Sidebar</option> <?php $sidebars = $wp_registered_sidebars;// sidebar_generator::get_sidebars(); if(is_array($sidebars) && !empty($sidebars)){ foreach($sidebars as $sidebar){ if($selected_sidebar[$i] == $sidebar['name']){ echo "<option value='{$sidebar['name']}' selected>{$sidebar['name']}</option>\n"; }else{ echo "<option value='{$sidebar['name']}'>{$sidebar['name']}</option>\n"; } } } ?> </select> with <select name="sidebar_generator_replacement[<?=$i?>]"> <option value="0"<?php if($selected_sidebar_replacement[$i] == ''){ echo " selected";} ?>>None</option> <?php $sidebar_replacements = $wp_registered_sidebars;//sidebar_generator::get_sidebars(); if(is_array($sidebar_replacements) && !empty($sidebar_replacements)){ foreach($sidebar_replacements as $sidebar){ if($selected_sidebar_replacement[$i] == $sidebar['name']){ echo "<option value='{$sidebar['name']}' selected>{$sidebar['name']}</option>\n"; }else{ echo "<option value='{$sidebar['name']}'>{$sidebar['name']}</option>\n"; } } } ?> </select> </li> <?php } ?> </ul> </div> </div> </div> </div> <?php } /** * called by the action get_sidebar. this is what places this into the theme */ function get_sidebar($name="0"){ if(!is_singular()){ if($name != "0"){ dynamic_sidebar($name); }else{ dynamic_sidebar(); } return;//dont do anything } global $wp_query; $post = $wp_query->get_queried_object(); $selected_sidebar = get_post_meta($post->ID, 'sbg_selected_sidebar', true); $selected_sidebar_replacement = get_post_meta($post->ID, 'sbg_selected_sidebar_replacement', true); $did_sidebar = false; //this page uses a generated sidebar if($selected_sidebar != '' && $selected_sidebar != "0"){ echo "\n\n<!-- begin generated sidebar -->\n"; if(is_array($selected_sidebar) && !empty($selected_sidebar)){ for($i=0;$i<sizeof($selected_sidebar);$i++){ if($name == "0" && $selected_sidebar[$i] == "0" && $selected_sidebar_replacement[$i] == "0"){ //echo "\n\n<!-- [called $name selected {$selected_sidebar[$i]} replacement {$selected_sidebar_replacement[$i]}] -->"; dynamic_sidebar();//default behavior $did_sidebar = true; break; }elseif($name == "0" && $selected_sidebar[$i] == "0"){ //we are replacing the default sidebar with something //echo "\n\n<!-- [called $name selected {$selected_sidebar[$i]} replacement {$selected_sidebar_replacement[$i]}] -->"; dynamic_sidebar($selected_sidebar_replacement[$i]);//default behavior $did_sidebar = true; break; }elseif($selected_sidebar[$i] == $name){ //we are replacing this $name //echo "\n\n<!-- [called $name selected {$selected_sidebar[$i]} replacement {$selected_sidebar_replacement[$i]}] -->"; $did_sidebar = true; dynamic_sidebar($selected_sidebar_replacement[$i]);//default behavior break; } //echo "<!-- called=$name selected={$selected_sidebar[$i]} replacement={$selected_sidebar_replacement[$i]} -->\n"; } } if($did_sidebar == true){ echo "\n<!-- end generated sidebar -->\n\n"; return; } //go through without finding any replacements, lets just send them what they asked for if($name != "0"){ dynamic_sidebar($name); }else{ dynamic_sidebar(); } echo "\n<!-- end generated sidebar -->\n\n"; return; }else{ if($name != "0"){ dynamic_sidebar($name); }else{ dynamic_sidebar(); } } } /** * replaces array of sidebar names */ function update_sidebars($sidebar_array){ $sidebars = update_option('sbg_sidebars',$sidebar_array); } /** * gets the generated sidebars */ function get_sidebars(){ $sidebars = get_option('sbg_sidebars'); return $sidebars; } function name_to_class($name){ $class = str_replace(array(' ',',','.','"',"'",'/',"\\",'+','=',')','(','*','&','^','%','$','#','@','!','~','`','<','>','?','[',']','{','}','|',':',),'',$name); return $class; } } $sbg = new sidebar_generator; function generated_dynamic_sidebar($name='0'){ sidebar_generator::get_sidebar($name); return true; } ?> </code>
|
you can do something like: <code> // create your own page add_menu_page('my-page', 'My Page', 'My Page', 'parent-slug', 'my_plugin_options', '', '10'); // create the subpage under my-page add_submenu_page('parent-slug', 'Sidebars', 'Sidebars', 'manage_options', __FILE__, array('sidebar_generator','admin_page')); </code> Note that the last parameter on add_menu_page is a 10. The higher the number the lower the position of the menu item. HTH
|
Add menu page issues (permissions & position)
|
wordpress
|
I'm executing a query inside of header.php which is apparently resetting the $post object so that all pages are getting the $post-> ID of the last element in this loop. <code> $mypostsheader = get_posts(array('cat' => "$cat,-$catHidden",'numberposts' => $cb2_current_count)); $current_page = get_post( $current_page );?> <div class="menu top"> <ul><?php foreach($mypostsheader as $idx=>$post){ if ( $post->ID == $current_page->ID )//do something; } </code> I've tried adding a rewind_posts() at the end of this function and also at the end of header.php but my echo $post-> ID inside of page.php still returns the id of the last element in the query. Any ideas?
|
I found that one solution for this was to place a call to wp_reset_query() just before the close of the function call. I was trying to use rewind_posts() but it would not work. wp_reset_query() did the trick. After doing that, thanks to @goldenapples excellent observation that I was already setting a pointer to the current $post object with my $current_page variable (duh!), I found that I could dump the wp_reset_query() call and instead just add this line in its place... <code> $post = $current_page; </code> The root cause is that I was resetting the $post object in the for loop (as $idx=> $post) and the query had to be reset so that the value of $post was a true reflection of the current $post object for the page in function calls below header.php
|
All post ids are the same after this query but rewind_posts() does not seem to work here?
|
wordpress
|
I have a website where I let people subscribe. I would like to only show the author page for actual authors who have written a post. I wrote this code that checks for post the problem is I can't use a <code> wp_redirect </code> or include a template that uses it because then I get everyones favorite "cannot redifine headers header" message. I could display a "User has no post message but I think redirecting them to the main author page is a better option. <code> if ( is_author() ) : ?> <?php $id = get_query_var( 'author' ); $post_count = get_usernumposts($id); if($post_count <= 0){ //This line could also be wp_redirect include( STYLESHEETPATH .'/author-redirect.php'); exit; } endif;?> </code> Thanks
|
You can do this at an earlier moment by hooking into the right action, like <code> template_redirect </code> , which fires right before the template will be displayed. <code> add_action( 'template_redirect', 'wpse14047_template_redirect' ); function wpse14047_template_redirect() { if ( is_author() ) { $id = get_query_var( 'author' ); // get_usernumposts() is deprecated since 3.0 $post_count = count_user_posts( $id ); if ( $post_count <= 0 ) { //This line could also be wp_redirect include( STYLESHEETPATH .'/author-redirect.php' ); exit; } } } </code>
|
How to hide/redirect the author page
|
wordpress
|
I just upgraded to WordPress 3.1.1 and suddenly I'm getting the following error: <code> Fatal error: Call to undefined function wp_get_current_user() in /home/arisehub/arisehub.org/wp-includes/capabilities.php on line 1028 </code> I've narrowed it down to my usage of "current_user_can" Example: <code> if ( !current_user_can('manage_options') ) { add_action('admin_init','customize_page_meta_boxes'); } </code> Removing that reference to current_user_can removes the errors. Any ideas?
|
You are calling the function too early. The <code> functions.php </code> is included before <code> current_user_can() </code> is defined. Never do anything before the hook <code> 'after_setup_theme' </code> : Example for the functions.php <code> add_action( 'after_setup_theme', array( 'WPSE_14041_Base', 'setup' ) ); class WPSE_14041_Base { public static function setup() { ! isset ( $GLOBALS['content_width'] ) and $GLOBALS['content_width'] = 480; add_theme_support( 'post-thumbnails', array( 'post', 'page' ) ); add_theme_support( 'automatic-feed-links' ); add_theme_support( 'menus' ); add_editor_style(); add_custom_background(); // You may use current_user_can() here. And more. :) } } </code>
|
current_user_can on WordPress 3.1.1
|
wordpress
|
I need to add a widget to the sidebar that shows post titles sorted by year ie: 2011 POST TITLE 1 POST TITLE 2 POST TITLE 3 2010 POST TITLE 1 POST TITLE 2 POST TITLE 3 I was thinking of using the Archive widget to do this, but I dont know how to add the display post title bit and then have the YEAR display as a type of heading for all the posts under that year. This might not be the best way to go... Any thoughts or feedback would be greatly appreciated
|
Have a look at http://wordpress.org/extend/plugins/simple-yearly-archive/ Or if you want to code it yourself have a look at wp_get_archives http://codex.wordpress.org/Function_Reference/wp_get_archives
|
Archive Widget - Show selected Category Post title. Sorted by Year
|
wordpress
|
Just like the title states. I've added around 20+ custom fields into my wordpress site and only around 10 are showing in the drop down. The custom fields are all functioning fine on the site side, but they just aren't showing up in the drop down.
|
There's a limit set inside the function that lists the meta data. http://core.trac.wordpress.org/browser/tags/3.1/wp-admin/includes/template.php#L512 Run a filter on <code> postmeta_form_limit </code> to increase to your desired value, eg. <code> add_filter( 'postmeta_form_limit', 'meta_limit_increase' ); function meta_limit_increase( $limit ) { return 50; } </code> Hope that helps.. :)
|
Added 20 Custom Fields. Only 10 showing in drop down
|
wordpress
|
The website I run www.detroitdungeon.com loads perfectly fine in every browser but in IE it crashes after loading. Any help would be appreciated!
|
When you want to debug any issue, follow these steps: Check Firefox or another browser to make sure it's not a system issue but is, in fact, a browser issue. Use the build-in debugger in IE to diagnose your problems. You've already done step 1. You've pointed out that the site works well everywhere but IE. I did step 2 for you. The site loads fine in IE until you hit the page onLoad event. Then, something fires that replaces your entire page content with the following: <code> <div id="stimuli_overlay" style="display: none;"/> <div id="stimuli_lightbox" style="display: none;"> ... </div> </code> This means your lightbox plugin is malfunctioning in IE. Try disabling it to verify (the site should start working in IE again). If it is the lightbox plugin, you'll need to find an alternative.
|
Website fully loads then immediately crashes in Internet Explorer
|
wordpress
|
I tried the following: <code> <?php function my_wp_admin_css() { echo '<link rel="stylesheet" href="/wp-content/plugins/custom-admin-style/wp-admin.css" type="text/css" />'; } add_action('wp_admin_css','my_wp_admin_css'); </code> but nothing is being displayed in the Wordpress admin. What I'm doing wrong?
|
You need to use <code> wp_enqueue_style </code> and hook it into <code> admin_print_styles </code> <code> add_action( 'admin_print_styles' , 'my_wp_admin_css' ); function my_wp_admin_css() { wp_enqueue_style('my_admin_style' , WP_PLUGIN_URL . '/myPlugin/stylesheet.css' ); } </code> If you just want the stylesheet on your plugins page you can use: <code> $mypage = add_management_page( 'myplugin', 'myplugin', 9, __FILE__, 'myplugin_admin_page' ); add_action( "admin_print_styles-$mypage", 'myplugin_admin_head' ); function myplugin_admin_head() { // what your plugin needs in its <head> } </code>
|
Can't call external stylesheet for Wordpress admin (using wp_admin_css)?
|
wordpress
|
I already use WordPress to create an online catalog and web presence. Now, a little box tells people to enter their email, and they will receive an email when a new product is added to the site (which is useful). Now, having entered the emails manually or asking people to enter it, I would like to have a little CRM for managing those mails, getting the names, phones, emails, addresses, and references (why they are in the database) - all in WordPress. So when new content is added, or when I would like to send all those people info (mass mailing), I can use the same system as for managing my site. What solutions have you tried and used for this?
|
Check out Bill Erickson's Twentyten CRM Theme . It's a great theme for using WordPress as a CRM.
|
CRM and newsletter integration?
|
wordpress
|
I'm using a custom post type with custom meta fields, but autosave and the "unsaved changes" dialog don't seem to be triggered for these custom meta fields. Autosave isn't as important to me as the unsaved changes dialog - is there a way to trigger it? <code> function add_meta_boxes() { add_meta_box('places_location', __('Location'), array(&$this, 'location_box'), 'place', 'normal', 'high'); } function location_box($post) { wp_nonce_field(plugin_basename(__FILE__), 'places_location_nonce'); $lat = get_post_meta($post->ID, 'places_lat', true); $lng = get_post_meta($post->ID, 'places_lng', true); ?> <p> <label> Latitude: <input name="places_lat" value="<?php echo esc_attr($lat); ?>" /> </label> <label> Longitude: <input name="places_lng" value="<?php echo esc_attr($lng); ?>" /> </label> </p> <?php } function save_place($id) { // skip unverified location nonces if(!wp_verify_nonce($_POST['places_location_nonce'], plugin_basename(__FILE__))) return; // skip autosave calls // commenting this out still doesn't trigger saving these fields on autosave //if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return; // update our custom post meta update_post_meta($id, 'places_lat', (float)$_POST['places_lat']); update_post_meta($id, 'places_lng', (float)$_POST['places_lng']); } </code>
|
The code indeed only looks at the TinyMCE editor or the title and content field if the editor is hidden: <code> window.onbeforeunload = function(){ var mce = typeof(tinyMCE) != 'undefined' ? tinyMCE.activeEditor : false, title, content; if ( mce && !mce.isHidden() ) { if ( mce.isDirty() ) return autosaveL10n.saveAlert; } else { title = $('#post #title').val(), content = $('#post #content').val(); if ( ( title || content ) && title + content != autosaveLast ) return autosaveL10n.saveAlert; } }; </code> You could replace that <code> onbeforeunload </code> handler with your own (be sure to include the existing functionality of course). Or play with the <code> isDirty() </code> state of the TinyMCE editor and that <code> autosaveLast </code> value?
|
Trigger "unsaved changes" dialog for custom post meta changes
|
wordpress
|
I have a widget that shows all the post names. All the post names are "Chapter ## - Title" I would like the php in the widget to remove the "Chapter 1 -" or "Chapter 12 -" for example so that just the part after the Chapter is left....
|
This is a new query loop that I use that shows the latest ten post titles/permalinks in the category mycategoryname and strips the first 15 characters from all of the titles. <code> <?php $my_query = new WP_Query('category_name=mycategoryname&showposts=10'); ?> <?php while ($my_query->have_posts()) : $my_query->the_post(); ?> <a href="<?php the_permalink() ?>" title="Permanent Link to: <?php the_title_attribute(); ?>"> <?php $mytitle = get_the_title(); $mytitle = substr($mytitle,15); echo $mytitle; ?></a> <?php endwhile; ?> </code> If you need to select which posts to strip either 8 or 10 characters, you'd have to select them by some sort of criterea and alternate that character number.
|
Removing the first 8-10 letters from a post?
|
wordpress
|
My theme uses some custom options fields, like post excerpt, that were removed from the editor screen with WP 3.1 I understand and support the intent to clean up the content workspaces. However, as a result of the 3.1 upgrade, I have had several support requests related to the fields that suddenly disappeared with 3.1 I issued a tech bulletin informing my theme owners of the change and how to get the excerpts field back using the "Screen options" button, but its still an issue for many users. Is it possible, from functions.php, to reset the screen options for a given WP screen? For example, I want to bring back the "excerpts" field to the post editor screen as well as the "Posts" selector when editing/creating "Custom Menus". PS: I understand that these options can be manually configured via "Screen options", but you might be surprised how many users have never seen or used that button :-) We tend to narrowly focus on the elements we are intent on working with at that instant and block out everything else. I do it myself and its human nature. Perhaps what we really need is a little electronic genie that whispers into our ear: "The field you are looking for, the one that was here before and is now gone, is behind that little button up there. Click it and you will open up a new wing of your WordPress world...and you will be better for it"
|
http://wordpress.org/support/topic/troubleshooting-wordpress-31-master-list?replies=14 a few posts down has instructions for default 'ON' options <code> // Change what's hidden by default add_filter('default_hidden_meta_boxes', 'be_hidden_meta_boxes', 10, 2); function be_hidden_meta_boxes($hidden, $screen) { if ( 'post' == $screen->base || 'page' == $screen->base ) $hidden = array('slugdiv', 'trackbacksdiv', 'postexcerpt', 'commentstatusdiv', 'commentsdiv', 'authordiv', 'revisionsdiv'); // removed 'postcustom', return $hidden; </code> }
|
How to programmatically bring back "excerpts" field in post editor in WP 3.1+
|
wordpress
|
I'm using the following code to display the term for a specified taxonomy: <code> $terms = get_terms( "book_review" ); $category = $terms[0]->name; </code> However I want to display the term for whatever the currently displayed taxonomy is, rather than specifying a particular taxonomy. Basically what I'm wanting is a way to replicate the functionality of get_the_category, but for the current taxonomy instead of the current category. I'm trying to display this on a single custom post type page (single-custom_post_type_name.php)
|
You can use <code> get_queried_object </code> to get the term name. <code> <?php if( is_tax() ) { global $wp_query; $term = $wp_query->get_queried_object(); $title= $term->name; } ?> </code> To display: <code> <?php echo $title; ?> </code> If your on a taxonomy archive page you can use: <code> <?php $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) ); ?> </code> Then to display the term: <code> <?php echo $term->name; ?> </code> T he following properties are available for the $term object : term_id name slug term_group term_taxonomy_id taxonomy description parent -count
|
How to get the first term for the current taxonomy?
|
wordpress
|
So basically i got this custom field value which is stored in $postrating - and under the database field customfield1. I want to grab the value of that field for all posts that have the tag currently being browsed. Then i want to calculate the average value of those numbers and display on the archive.php page when browing a tag.
|
If its a regular custom field you can add this to your archive.php: <code> //before the loop $rating_count = 0; $total_rating = 0; //in the loop $total_rating = $total_rating + get_post_meta($post->ID,'your_custom_field_name',true); $rating_count = $rating_count + 1; //after the loop: $average = $total_rating / $rating_count; echo 'the average rating for this tag is: ' . $average; </code> Update Now that you've mentioned that there is pagination evolved and you are not getting all of the posts (for example 10/14), you can create a new WP_Query object and use it to get all of the posts (14/14) and check the average. add this code before your loop: <code> global $wp_query; $real_query = $wp_query->query; //save reall query //create new query for all posts of the tag/category/whatever $args = array_merge( $wp_query->query, array( 'posts_per_page' => '-1' ) ); $average_q = new WP_Query($args); $rating_count = 0; $total_rating = 0; while ($average_q->have_posts()){ $average_q->the_post(); $total_rating = $total_rating + get_post_meta($post->ID,'your_custom_field_name',true); $rating_count = $rating_count + 1; } wp_reset_query(); $average = $total_rating / $rating_count; echo 'the average rating for this tag is: ' . $average; query_posts($real_query); </code>
|
Getting and calculating averge value of custom fields of the same tag
|
wordpress
|
I've created a site using wordpress and i moved that from localhost to new server. The steps i've followed is just got backup of old db from localhost and uploaded them to the new server. Changed the WordPress address (URL) & Site address (URL) manually from phpmyadmin. Moved all the files from localhost to the server Changed the wp-config with the new server's db details. Now i'm able to visit the admin panel of wordpress but not the site. Its showing the following error, The page isn't redirecting properly Firefox has detected that the server is redirecting the request for this address in a way that will never complete. This problem can sometimes be caused by disabling or refusing to accept cookies. I think that this must some redirection problem.. My new .htaccess file under new server is <code> <IfModule mod_rewrite.c> RewriteEngine On RewriteBase /veejata/wordpress/ RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /veejata/wordpress/index.php [L] </IfModule> </code>
|
I solved it myself.. It was issue in the windows server with wordpress 3.1 so i installed the Permalink fix pack @ wordpress.org/extend/plugins/… . Now its working fine.. I've no issues linux server.. I've to dive into the thing to know why that is happening in windows server...
|
Wordpress redirection problem after moving to a new server?
|
wordpress
|
Is there any information about WordPress becoming completely OOP in future versions?
|
Hi @Eugene: I can say with about 99.9999% certainty that WordPress will never become completely OOP in future version, not the least of which is that the topic has come up time and again on the wp-hackers list and the core team members has expressed no interest in doing so. As I look at my personal experience with programming and teaching OOP starting around 1990 I agree with the core team and think complete OOP would be a mistake. Although I once an OOP zealot and thought OOP was a panacea I've since come to believe that it has its value in some contexts but in other contexts it gets in the way. One of the biggest problems I've found with OOP is that it forces the developer to bake in structure long before the developer actually understands what that structure should be which then leads to the fragile base-class problem . Of course for selected aspects of WordPress, OOP makes a lot of sense and if you study core you'll find such classes; Widget, List_Tables (in 3.1), etc. At this point I'm happy to work with WordPress in a mostly non-OOP paradigm and think that if it had been pure OOP WordPress would have never gained the following it has. Why? Because OOP would have raised the bar of complexity for would-be WordPress themers and plugin developers, and it would likely have resulted in an application that was not flexible enough to evolve as the core team learned more about the needs of its users over the past 6 years. FWIW.
|
Will WordPress become completely OOP?
|
wordpress
|
Basically, I would like to activate a CSS class only if the current page is a certain custom post type (e.g. <code> ?bbp_forum=technology </code> ) or if the current page is a child of that custom post type. EDIT: The first custom post type is called ' <code> bbp_forum </code> .' Each ' <code> bbp_forum </code> ' can have a ' <code> bbp_topic </code> ' (which is another custom post type). Like it is described in this picture: I used to do the following in order to assign the class <code> current </code> to the current ' <code> bbp_forum </code> 's link: <code> <?php global $post; $the_post_ID = $post->ID; $cat_posts = get_posts('post_type=bbp_forum&posts_per_page=-1'); var_dump($the_post_ID); ?> <?php foreach ( $cat_posts as $post ) : ?> <li <?php if ( $post->ID == $the_post_ID ) echo 'class="current"'; ?>> <a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a> </li> <?php endforeach; ?> </code> but it doesn't work for a child of the ' <code> bbp_forum </code> '
|
I accidentally got the answer: <code> <?php global $post; $the_post_parent = $post->post_parent; $the_post_ID = $post->ID; $cat_posts = get_posts('post_type=bbp_forum&posts_per_page=-1'); print_r($post_parent); ?> <?php foreach ( $cat_posts as $post ) : ?> <li <?php if ( $post->ID == $the_post_ID || $post->ID == $the_post_parent ) echo 'class="current"'; ?>> <a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyten' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a> </li> <?php endforeach; ?> </code> I would appreciate if someone explain it to me.
|
How to write an if statement which reads: 'if is this custom post type or a child of it do the following'?
|
wordpress
|
I want to have different sidebars on different pages. So firstly I registered a few basic sidebars in functions.php. So they will be always there no matter where I move my theme. Let's name them Standard Sidebar, Special Sidebar, Tiny Sidebar. The next step was creating sidebars metabox below posts and pages. It lists all the sidebars using foreach $GLOBALS['wp_registered_sidebars'] loop and allows user to pick one. Now, here comes the trouble. I don't know how to display my sidebars. I have a meta value but get_sidebar() accepts only names from sidebar.php file. What about registered (not included in sidebar.php) sidebars? I know I could add all my sidebars to sidebar.php/save them as sidebar-name.php, but again, I'm going to use sidebar generator to add addtional sidebars to three basic ones. Any ideas, walk-troughs how to accomplish this? Displaying registered sidebars by name will be a serious breakthrough in my case.
|
You can call registered sidebars with the dynamic_sidebar() function. Just put the ID of the sidebar in to the call. In the case below the id would be homepage-sidebar. <code> <?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('homepage-sidebar') ) : ?><?php endif; ?> </code>
|
Custom sidebars - get_sidebar() problems
|
wordpress
|
When I do <code> $gallerypage = new WP_Query(array( 'post_type' => 'post', 'pagename' => 'gallery' )); $gallerypage->the_post(); </code> the last line <code> $gallerypage->the_post(); </code> is giving me errors. Why is that? It seems correct? <code> Notice: Undefined offset: 0 in /site/url/wp-includes/query.php on line 2719 Notice: Trying to get property of non-object in /site/url/wp-includes/query.php on line 3491 Notice: Trying to get property of non-object in /site/url/wp-includes/query.php on line 3493 Notice: Trying to get property of non-object in /site/url/wp-includes/query.php on line 3495 Notice: Trying to get property of non-object in /site/url/wp-includes/query.php on line 3496 Notice: Trying to get property of non-object in /site/url/wp-includes/query.php on line 3503 Notice: Trying to get property of non-object in /site/url/wp-includes/query.php on line 3514 Notice: Trying to get property of non-object in /site/url/wp-includes/post-template.php on line 30 Notice: Trying to get property of non-object in /site/url/wp-includes/post-template.php on line 30 </code> wp-includes/query.php line 2717 onwards <code> $this->current_post++; $this->post = $this->posts[$this->current_post]; // error here? </code>
|
Hi @JM at Work: Try wrapping <code> $gallerypage->the_post(); </code> with <code> if ($gallerypage->have_posts()): ... endif; </code> It should look like this: <code> if ($gallerypage->have_posts()): $gallerypage->the_post(); endif; </code> See: http://codex.wordpress.org/The_Loop
|
WP_Query $gallerypage-> the_post() giving Undefined offset: 0
|
wordpress
|
i need to change the posts in taxonomy.php page. I have a meta_key which i want to compare to meta value. But currently my code is not returning anything. I am sure i am missing something. Please let me know what i am doing wrong! <code> add_action('pre_get_posts', 'add_event_date_criteria'); function add_event_date_criteria(&$query) { // We only want to filter on "public" pages // You can add other selections, like here: // - Only on a term page for our custom taxonomy if (!is_admin() && is_tax('event-tag') || is_tax('event-category')) { $query->set('meta_key', 'start_time'); $query->set('meta_compare', '>='); $query->set('meta_value', time()); $query->set('meta_key', 'start_time'); $query->set('orderby', 'meta_value_num'); $query->set('order', 'ASC'); } } </code>
|
Try using meta_query parameter : <code> add_action('pre_get_posts', 'add_event_date_criteria'); function add_event_date_criteria(&$query) { // We only want to filter on "public" pages // You can add other selections, like here: // - Only on a term page for our custom taxonomy if (!is_admin() && is_tax('event-tag') || is_tax('event-category')) { $time = time(); $meta = array( array( 'key' => 'start_time', 'value' => $time, 'compare' => '>=' ) ); $query->set('meta_query',$meta ); $query->set('meta_key', 'start_time'); $query->set('orderby', 'meta_value_num'); $query->set('order', 'ASC'); } } </code> also you need to make sure your meta field <code> start_time </code> is measured and saved in the number of seconds since the Unix Epoch like time() function.
|
pre get posts changing the query
|
wordpress
|
I'm looking for themes or examples of sites that use the post format feature in an interesting way. I suppose adding special styling for each post format would be a good start. But if anyone knows of it being used in a cool or creative ways by a premium or free theme feel free to chime in.
|
Check out this post on WordCast: WordPress Post Format Eye-Candy: Tumblr Style Theme Inspiration Showcase Also Digging into WordPress uses them and just wrote a post about it: Tumblr Links with Post Formats
|
Suggestions for creative use of post format feature, or themes that use them well
|
wordpress
|
I'm going to be using add_role() and $role-> add_cap() to set up a new custom role and attach a new capability to existing roles. I'm wondering where the best place to do this is? Obviously I can do it straight inside functions.php and be done with it. But is this the best practice? Do I only need to do this on admin_init? or should I do it on init? I'm not entirely sure what the best practices are around using init action hooks rather than just dropping a direct function call inside functions.php. thanks for your input!
|
When adding a role and capabilities you only need to run the code once since the roles and capabilities are saved to the database when using <code> add_role </code> or <code> ->add_cap </code> functions so just like Andy said you can use <code> after_setup_theme </code> for this kind of action but add some kind of check so it only runs once, like register_activation_hook or using options: <code> add_action('after_setup_theme','my_add_role_function'); function my_add_role_function(){ $roles_set = get_option('my_roles_are_set'); if(!$roles_set){ add_role('my_role', 'my_roleUser', array( 'read' => true, // True allows that capability, False specifically removes it. 'edit_posts' => true, 'delete_posts' => true, 'upload_files' => true )); update_option('my_roles_are_set',true); } } </code>
|
What action should I hook into when adding roles and capabilities?
|
wordpress
|
I am a programmer, and love jQuery. Visual jQuery and other resources is THE best place to get all the code/function et get your hand dirty... But when it come to WordPress.. the code is too thin or too abstract... i nee more like a dictionary of term, function, and possibility What i need is like the ULTIMATE cheat sheet, made in a bible.. i don't care if it 20 pages, i need an HOW TO book of the function possible... like : wp_list_categories.. where it is and what are the the return values this snippet i copy from the web : <code> <?php foreach (get_the_category() as $cat){ echo "[" . $cat->cat_name . "] ";} ?> </code> the method cat_name HOW SHOULD I KNOW THAT ???? where to find the reference ?? please enlight me !
|
Hi @menardmam: Let's try with what I wrote in the question : <code> $cat->cat_name </code> . How can I know that <code> cat_name </code> is a method that return something from <code> $cat </code> from <code> get_the_category() </code> function? Frankly the best way to know an answer like that is to use a debugging IDE and to trace through the WordPress core source code. Seriously; the source code is the only documentation that is sure to have been updated, and the results shown in the debugger are the only documentation that is sure to be exactly correct. I use PhpStorm+Zend Debugger but others use NetBeans, others Eclipse, and there are several other PHP IDEs with debuggers too. Next, you can "google" for your specific questions by including <code> site:codex.wordpress.org </code> as part of your search term and/or search for it here on this site. As a third and often best way, ask a specific question here on this site . This site works best when you ask specific "How-To" questions with a title that matches your question and with details about your question , and especially your use-case when applicable. Think about it this way: If someone googles to find the answer you are after, would google ever match their search terms with the title of your question? And when they do find your question would it be very clear to them what question you were asking? If you can answer "Yes" to both of those then chances are very good you'll get a great answer to your specific question here and you will be likely to get it quickly.
|
Need resource on available functions and objects
|
wordpress
|
for a small project i need to assign the The Events Calendar Plugin to an subpage but i've found no solution in the documentation. Does anyone know if this is possible or has an idea to get it done? Regards
|
Here's a basic page template for displaying an events calendar in grid form based on the grid template bundled with the plugin. Edit as necessary to match the styling and layout of your theme: <code> <?php /** * Template Name: Event Gridview **/ global $spEvents; $spEvents->loadDomainStylesScripts(); get_header(); query_posts('post_type=post&category_name=Events&posts_per_page=-1'); ?> <div id="tec-content" class="grid"> <div id='tec-events-calendar-header' class="clearfix"> <h2 class="tec-cal-title"><?php _e('Calendar of Events', $spEvents->pluginDomain) ?></h2> <span class='tec-month-nav'> <span class='tec-prev-month'> <a href='<?php echo events_get_previous_month_link(); ?>'> &#x2190; <?php echo events_get_previous_month_text(); ?> </a> </span> <?php get_jump_to_date_calendar( "tec-" ); ?> <span class='tec-next-month'> <a href='<?php echo events_get_next_month_link(); ?>'> <?php echo events_get_next_month_text(); ?> &#x2192; </a> </span> </span> <span class='tec-calendar-buttons'> <a class='tec-button-off' href='<?php echo events_get_listview_link(); ?>'><?php _e('Event List', $spEvents->pluginDomain)?></a> <a class='tec-button-on' href='<?php echo events_get_gridview_link(); ?>'><?php _e('Calendar', $spEvents->pluginDomain)?></a> </span> </div><!-- tec-events-calendar-header --> <?php global $wp_query; $tecCatObject = get_category( $wp_query->query_vars['cat']) ?> <a class="ical" href="<?php bloginfo('home'); ?>/?ical=<?php echo $tecCatObject->slug; ?>"><?php _e('iCal Import', $spEvents->pluginDomain) ?></a> <?php event_grid_view(); // See the plugins/the-events-calendar/views/table.php template for customization ?> </div> <?php /* For custom template builders... * The following init method should be called before any other loop happens. */ wp_reset_query(); $wp_query->init(); ?> <?php get_footer(); ?> </code> The key component being the <code> query_posts </code> call after the header is called. You can use this to modify the other template files in the views subfolder of the plugin to adapt the other calendar views into additional page templates. I have tested this using the free version of the plugin linked in Wordpress v3.2.1, no shortcodes necessary.
|
Assign "The Events Calendar" to Subpage
|
wordpress
|
First a teeny bit of background... I have a custom post type where I'd like to use custom post statuses. Since custom post statuses (stati/status/whatever) , have not been fully implemented within the core, I've decided to use the gettetext filters to change the names of certain things. For example, I've changed the text "Publish" on the publish button to say "Save". I went with something like stackexchange-url ("Rarst's approach here"). A summary of my code is below. I'm really not going for anything drastic here as far as changing what each status does/is. Anyway, the translation works just fine as far as PHP is concerned. However, while testing, I realized that if I click the Edit link within the misc publishing actions div, then click the cancel link that subsequently appears, my translated "Save" button will revert to a "Publish" button. This seems to happen as a result of the javascript function <code> updateText() </code> found in <code> /wp-admin/js/post.dev.js </code> . I'm looking for a way to keep the JS from stomping my translation. I'd prefer not to just mess with it using DOM manipulation, but if that's my only option, I'll go for it. I'm running 3.1, btw. <code> <?php class MyClass { function __contsruct() { add_action( 'admin_head', array ( &$this, 'load_gettext_filters' ) ); } function load_gettext_filters() { add_filter( 'gettext', array ( &$this, 'change_publishing_text' ), 10, 2 ); } function change_publishing_text( $translation, $text ) { global $post; if ( ! isset ( $post->post_type ) ) { return $translation; } if ( 'mypost' === $post->post_type ) { if ( ( 'Publish' === $text ) ) { return 'Save'; } } return $translation; } } </code>
|
First, you have nasty typo in <code> __contsruct </code> . :) Second, your hook timing is wrong. Related WP JavaScript is localized via <code> postL10n </code> object (you can see it echoed in page's source), that gets put together on <code> init </code> hook - way earlier then <code> admin_head </code> and your filter is not in place yet. From quick test this should do it: <code> add_action( 'init', array ( &$this, 'load_gettext_filters' ), 9 ); </code> Update Ok, scratch that. Won't work if we need context. Let's try this: <code> add_action('admin_footer', array ( &$this, 'localize_post_script' ) ); function localize_post_script() { global $wp_scripts; $wp_scripts->registered['post']->extra['l10n'][1]['publish'] = __('Publish'); } </code>
|
How to prevent text modified using gettext filter being stomped (presumably) by updateText() js function within a CPT's edit screen
|
wordpress
|
I have the following code: <code> <?php /* Template Name: blog */ ?> <?php get_header(); ?> <div id="blog"> <div class="content"> <?php query_posts('cat=-4,-11');?> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div class="post"> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <span class="date"><?php the_time('F jS, Y'); ?></span> <div class="body"> <?php the_content(''); ?> </div> <span class="info">posted by: <?php the_author(); ?> in <?php the_category(', '); ?> | <?php comments_popup_link('No Comments', '1 Comment', '% Comments'); ?></span> </div> <?php endwhile; endif; ?> <?php posts_nav_link(' &#183; ', '&laquo; previous page ', ' <br />next page &raquo; '); ?> </div> <?php get_sidebar(); ?> </div> <?php get_footer(); ?> </code> The page navigation is only needed in this template.
|
You would need to account for pagination in your query.... something like: <code> <?php query_posts( array( 'cat' => '-4,-11', 'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1 ), )); ?> </code> http://www.rvoodoo.com/projects/wordpress/wordpress-tip-fixing-pagination-on-custom-queries-with-query_posts/
|
Post Navigation Not Working In Blog Template - Redirecting to same page with correct URI
|
wordpress
|
How might I query for a tag given the slug?
|
Hi @JM at Work: Like this: <code> $term_slug = 'foo'; $term_object = get_term_by( 'slug', $term_slug, 'post_tag' ); print_r( $term_object ); </code>
|
Query for tag given slug
|
wordpress
|
Normal Wordpress Menu looks like: Home | Blog | About us | Contact But I've seen many pages with descriptions under these links: Home Page | Our Blogs | About us | Contact ....meet us...| read more| basic info| contact form How to achieve this? (I want it to be core function for all my themes, so no plugins please, I just want to know how it's done)
|
You need a custom walker for the nav menu. See this article for the details. Basically, you add a parameter <code> 'walker' </code> to the <code> wp_nav_menu() </code> options and call an instance of an enhanced class: <code> wp_nav_menu( array ( 'menu' => 'main-menu', 'container' => FALSE, 'container_id' => FALSE, 'menu_class' => '', 'menu_id' => FALSE, 'depth' => 1, 'walker' => new Description_Walker ) ); </code> The class <code> Description_Walker </code> extends <code> Walker_Nav_Menu </code> and changes the function <code> start_el( &$output, $item, $depth, $args ) </code> to look for <code> $item->description </code> . A basic example: <code> /** * Create HTML list of nav menu items. * Replacement for the native Walker, using the description. * * @see stackexchange-url * @author toscho, http://toscho.de */ class Description_Walker extends Walker_Nav_Menu { /** * Start the element output. * * @param string $output Passed by reference. Used to append additional content. * @param object $item Menu item data object. * @param int $depth Depth of menu item. May be used for padding. * @param array $args Additional strings. * @return void */ function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { $classes = empty ( $item->classes ) ? array () : (array) $item->classes; $class_names = join( ' ' , apply_filters( 'nav_menu_css_class' , array_filter( $classes ), $item ) ); ! empty ( $class_names ) and $class_names = ' class="'. esc_attr( $class_names ) . '"'; $output .= "<li id='menu-item-$item->ID' $class_names>"; $attributes = ''; ! empty( $item->attr_title ) and $attributes .= ' title="' . esc_attr( $item->attr_title ) .'"'; ! empty( $item->target ) and $attributes .= ' target="' . esc_attr( $item->target ) .'"'; ! empty( $item->xfn ) and $attributes .= ' rel="' . esc_attr( $item->xfn ) .'"'; ! empty( $item->url ) and $attributes .= ' href="' . esc_attr( $item->url ) .'"'; // insert description for top level elements only // you may change this $description = ( ! empty ( $item->description ) and 0 == $depth ) ? '<small class="nav_desc">' . esc_attr( $item->description ) . '</small>' : ''; $title = apply_filters( 'the_title', $item->title, $item->ID ); $item_output = $args->before . "<a $attributes>" . $args->link_before . $title . '</a> ' . $args->link_after . $description . $args->after; // Since $output is called by reference we don't need to return anything. $output .= apply_filters( 'walker_nav_menu_start_el' , $item_output , $item , $depth , $args ); } } </code> Or, alternatively stackexchange-url ("as @nevvermind commented"), you could inherit all the functionalities of the parent's <code> start_el </code> function and just append the description to <code> $output </code> : <code> function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { parent::start_el($output, $item, $depth, $args); $output .= sprintf('<i>%s</i>', esc_html($item->description)); } </code> Sample output: Now enable the description field in <code> wp-admin/nav-menus.php </code> to get the ability to edit this field. If you don’t WP just trashes your complete post content into it. Further reading: Associated bugs stackexchange-url ("Similar example with different markup and formatting") stackexchange-url ("Enable description box in menu management screen programmatically") stackexchange-url ("Collect the item description for later usage") And that’s it.
|
Menu items description? Custom Walker for wp_nav_menu()
|
wordpress
|
I've been building wordpress sites for a few years now and have noticed a few things that bother me. 1. It's fairly slow (awful blanket statement, I apologize) My initial desire to create a custom front-end came from an observation. The Wordpress sites I was building weren’t quite as fast as I wanted them to be (3-5 seconds, sometimes longer). @Kenrik - They certainly were deployed on oversold shared-hosting, but they got good Yslow scores. I tried it out and found the sites to be approximately three times faster when I didn’t load the WP overhead. Same machine, same Yslow score, 3 times faster. I’m no expert on Wordpress CPU usage, but I’ve read that it’s pretty intense, so I was not surprised by the speed gains I achieved. 2. It's often overly complex for the needs of a simple website Just a note: I’m mostly building sites for fashion lines and portfolio management, complex in front-end interaction, but with relatively little data. These sites are never going to be huge and they require very little code to retrieve the necessary content. My question is therefore largely theoretical. I think that Wordpress is a fantastic platform and that it has few limits for growth, however I think that loading all of its resources is overkill for a lot of smaller projects, destined to be served from shared hosting. 3. It has a lot of security issues (especially when using plugins) Concerning security, I can see how my question was ambiguous and contradictory. What I meant is that from my understanding, a Wordpress site, beyond any actual security holes, is vulnerable because attackers know that it is a Wordpress site. This creates a challenge (to breach a popular platform) and an inherent cheat sheet (Wordpress vulnerabilities are well documented). So, sure a custom solution might have more actual security holes, but I’m wondering if it this wouldn’t be balanced by the fact that it makes the inner workings anonymous. As @Kenrik said, “they most likely wont even bother because who cares about hacking a single site with iffy custom code?” 4. It's difficult to optimize page-load times What I meant by the difficulty of page-load optimization is that if one achieves interactive functionality via lots of plugins, many scripts are loaded and it becomes more tedious to go back and combine, modify, customize or optimize them. I find it easier to include jQuery plugins outside of Wordpress and not have to deal with how they hook into wp_head. So recently I decided to go about my development differently and use Wordpress as only a back-end tool. I use the admin space to update content and populate the database but I use a custom data access layer and custom functions on the front-end to retrieve and display the content. For pages where login is needed, I include the blog-header file and use wordpress' credential management functionalities. As I see it, the pros of this independent front-end solution are that it makes development easier (you only write what you need, and it's all your own work), it's easier to optimize page-loads (you have better control over what scripts are used and how to combine them in optimal ways), you are not alerting the entire hacking world to the existence of a wordpress install (because the files aren't loaded from a theme anymore) and more. Potential Cons: Security, lack of scalability, lack of developer support for custom solutions... Anything else ? I really enjoy creating sites outside of the wordpress constraints, I'm just worried I might be overlooking some major issues with this approach. Please let me know if this is the case. Cheers To retroactively conclude: I’m 100% sure that my sites are faster in the exact same environment when I don’t use the native Wordpress front-end. I’m doubt that my code is as safe as Wordpress, but I think that I can lock it down and the fact that it has an anonymous front-end might make it less of a target. I’m sure that I can code functionalities a lot faster when I deploy an extremely simple custom front-end solution. So I’m just wondering, given my environment and my constraints whether doing this is still just a bad idea. And if so, what are the main reasons. I’m sure there are other curious, ambitious, under-educated coders out there who might be wondering the same thing. They will likely benefit from whatever you have to say about the subject. Thank you all
|
You do cite experience with WP going back farther than that of mine... Yet I do not see these issues as that major. What scale of sites are we talking about? It's fairly slow I feel this is bit too much of generalization. Slow can be put in context of specific hardware, tasks and level of traffic. It's blanket statement otherwise. It's often overly complex for the needs of a simple website Complex for whom? Users? Developer? WP is trivial to install and get running. Create some content and you have that simple site. Where is complexity here? It has a lot of security issues (especially when using plugins) Again, bit too much of blanket statement. WP itself is relatively secure and most of security issues that had major impact seems to be from running grossly outdated WP versions. State of plugins and security is definitely far from perfect, but nothing prevents to be very selective or developing secure and reliable plugins, right? It's difficult to optimize page-load times Again, I am not sure what scale are we talking about. Optimization from low to mid sized sites seems trivial - install good static cache plugin, buff with opcode caching... Throw in alternative web server or reverse proxy if really needed. I really enjoy creating sites outside of the wordpress constraints, I'm just worried I might be overlooking some major issues with this approach. I pretty much have only one question for you - are you absolutely sure that you are doing it better, faster and more secure than native WP front-end? I do not ask this sarcastically, I think it might be plausible that for very narrow task custom-made and locked down front-end might be reasonable. But I also notice that overconfidence about custom solution being "just better" than collective work of many developers/companies is not uncommon in web development. Update My initial desire to create a custom front-end came from an observation. The Wordpress sites I was building weren’t quite as fast as I wanted them to be (3-5 seconds, sometimes longer). [...] They certainly were deployed on oversold shared-hosting, but they got good Yslow scores. YSlow (and PageSpeed) are excellent tools, but they are inherently limited. They can only analyze and advise on front-end performance and how site is processed by browser. They give no insight in your server performance and blindly chasing high front-end scores can actually be harmful to server load. You should use such tools, but you should never limit your insight in how site performs to them alone. On hosting - any dynamic site on shared hosting will choke under high load. Again, while it may seem easy to tweak and get high front-end scores, on the server side shared hosting critically lacks hardware and web stack flexibility, necessary for site with high traffic and/or striving for fast load times. I think that loading all of its resources is overkill for a lot of smaller projects, destined to be served from shared hosting. Had you tried static page caching? It effectively removes WP core out of most requests and it's about as fast as you can get on shared hosting. If you tried and not satisfied with pages, served from static cache, WordPress is not your problem - hosting is. What I meant is that from my understanding, a Wordpress site, beyond any actual security holes, is vulnerable because attackers know that it is a Wordpress site. This creates a challenge (to breach a popular platform) and an inherent cheat sheet (Wordpress vulnerabilities are well documented). There are no public and known security vulnerabilities in stable WordPress version. Those that arise are fixed in matter of hours. Poor server configuration (common occurrence on cheap hosts) or running outdated WP version is what gets you hacked, not the sheer fact of using WP. What I meant by the difficulty of page-load optimization is that if one achieves interactive functionality via lots of plugins, many scripts are loaded and it becomes more tedious to go back and combine, modify, customize or optimize them. I find it easier to include jQuery plugins outside of Wordpress and not have to deal with how they hook into wp_head. Yes, some plugins have no clue how to properly load scripts. That is really arguments for picking plugins carefully, not against WordPress core. Concatenating and optimizing scripts is trivial with good caching plugin. Overall and after your updates I feel that you are too eager to discard WordPress for issues that are inherent to any complex and fully-featured CMS (you need decent hosting to get it snappy) and you hadn't spend much time looking into caching solutions. It just might not be a good fit for the type of sites you build and you are better off looking into lighter, simpler and less functional CMS that will perform better under your hosting constraints.
|
What are the pros and cons of using a custom front-end to retrieve content from a Wordpress back-end
|
wordpress
|
I have a restricted area on a website that can only be accessed by logged in users. For that I created a page template with a 'current_user_can()' condition. My problem is that the documents attached to the restricted pages are still accessible to anyone if you put the complete path into the browsers address bar. Is there a way to restrict the access to uploaded files ? EDIT : I want to clarify, the files should be accessible only to logged in users.
|
This isn't really a WordPress question - but you can add a rewrite rule to prevent access unless the referrer is your own domain. [Update] You'll need to do 2 things Add a rewrite rule (either directly with .htaccess or by using WP_rewrite (Codex reference) . The aim here is to deny requests to your documents that don't have your domain as a referrer - this stops people pasting the link into a browser's address bar Wrap your download links in an <code> is_user_logged_in </code> (Codex reference) conditional block - that way they will only show up on the page if the user is logged in A code example is available in a related question: stackexchange-url ("protect wordpress uploads, if user is not logged in")
|
How to restrict access to uploaded files?
|
wordpress
|
I am using the following code to remove the admin bar (client request). <code> add_filter( 'show_admin_bar', '__return_false' ); </code> Trouble is, it leaves some autogenerating CSS, which places a massive white line at the top of my page in its place (via a 28px top margin rule). How can I turn this off as well?
|
To completely remove the Admin bar deregister the js and css using wp_degregister_script and remove the action. <code> if (!is_admin() && !current_user_can('add_users')){ wp_deregister_script( 'admin-bar' ); wp_deregister_style( 'admin-bar' ); remove_action('wp_footer','wp_admin_bar_render',1000); } </code>
|
Admin Bar CSS left over after removal
|
wordpress
|
Hey guys, last days i have been trying to figure out how to do that. As read on http://net.tutsplus.com/tutorials/javascript-ajax/create-a-twitter-like-load-more-widget/ but inside wordpress. And i have finally come with a solution, may not be the best one but i hope you guys can improve my code and post it here just like i`m doing. Feel free to use it wherever you want. (my coding skills are really bad so First you need to include jquery on your header. Insert this code on the page you wanna display the posts: <code> <?php session_start(); $number_of_posts = 3; if (!$_SESSION['posts_start']) { $_SESSION['posts_start'] = 0; } $_SESSION['posts_start'] = $_SESSION['posts_start'] ? $_SESSION['posts_start'] : $number_of_posts; $total_posts = wp_count_posts('post'); $total_posts = $total_posts->publish; ?> <script type="text/javascript"> jQuery(document).ready(function(){ var initialPosts = <?php echo my_get_posts(0, 5); ?>; var postHandler = function(postsJSON) { jQuery.each(postsJSON,function(i,post) { // Salva as variáveis de cada post var postURL = post.permalink; var postCOMMENTS = post.comments; var postTITLE = post.title; var postDATE = post.date; var postAUTHOR = post.author; // Coloca as variáveis na lista jQuery(".lista-artigos") .append("<li><span class=\"comentarios-artigo\">" + postCOMMENTS + "</span><h2><a href=\"" + postURL +"\">" + postTITLE + "</a></h2><span class=\"data-artigo\">Postado em " + postDATE + " por " + postAUTHOR + "</span></li>") }); }; postHandler(initialPosts); var totalposts = <?php echo $total_posts; ?>; var start = <?php echo $_SESSION['posts_start']; ?>; var desiredPosts = <?php echo $number_of_posts; ?>; jQuery('#load-more').click(function(){ jQuery('#load-more').removeClass('carregar').addClass('ativado').text('Loading...'); jQuery.ajax({ url: 'http://yoursite/wp-content/themes/yourtheme/mais-posts.php', data: { 'start': start, 'desiredPosts': desiredPosts }, type: 'get', dataType: 'json', cache: false, success: function(responseJSON) { jQuery('#load-more').text('Load More'); start += desiredPosts; postHandler(responseJSON); }, error: function() { jQuery('#load-more').text('Ops! Try Again.'); }, complete: function() { jQuery('#load-more').removeClass('ativado').addClass('carregar'); if (totalposts <= start) { jQuery('#load-more').hide(); } } }); }); }); </script> </code> Create a php file inside your themes folder (mine is called mais-posts.php) with the following code: <code> <?php require( '../../../wp-load.php' ); if(isset($_GET['start'])) { echo my_get_posts($_GET['start'], $_GET['desiredPosts']); $_SESSION['posts_start'] += $_GET['desiredPosts']; exit(); } ?> </code> I hope it may help anyone who is looking for something like this. So if you have any suggestion to this code please post below.
|
For starters see AJAX in Plugins . WordPress has own mechanism for processing Ajax request and that is what you should use over includging <code> wp-load.php </code> .
|
How to create a load more post entries like Twitter?
|
wordpress
|
i'm trying to get the author name using the " <code> the_author_meta </code> " function. After doing that I need to pass the value inside an array and return that with "json_encode". Let me show: <code> $autor_id = $post->post_author; $autor_name = the_author_meta('user_nicename', $autor_id); echo $autor_name; </code> The <code> $autor_name </code> <code> echo </code> works fine but when i do the following code it returns null on my script: ... <code> $results['author'] = $autor_name; $posts[] = $results; } return json_encode($posts); </code> it returns that: <code> "author":null </code> How can i make it display the author name like: <code> "author":admin </code> ?
|
The echoing is already done by the_author_meta(). <code> echo $autor_name </code> does nothing. Correct would be to use get_the_author_meta().
|
How to get post author name by its ID inside a function?
|
wordpress
|
i have a self hosted wordpress install on a server in a virtbox at home. i was trying out plugins from the wordpress.org site, and after enabling some securtiy plugins, i found i couldnt access the wp-login.php page anymore. i get a function of one of the plugins telling me the site is forbidden and doesnt exist. the problem is, i am not exactly sure which plugin did this. i dont have a login link on the front end of the page also. the plugins i have installed are bulletproof security, lockdown wp-admin, ultimate security checker, and wp security scan. the install is on an ubuntu server with no GUI, host is mac osx, but i can access it from the network. if i just delete the plugins from the wordpress directory, will that work?
|
Assuming you have shell access to the server (which is sounds like you do), rename the <code> wp-content/plugins </code> directory to something else (I often just stick an <code> x </code> in front) and see if you can get into your site. Then create a new plugins directory and move the plugins one at a time from <code> xplugins/ </code> to <code> plugins/ </code> . You'll soon know who the culprit is.
|
How do i login when i cant access wp-login.php?
|
wordpress
|
Does anyone know how much do the localization functions from WordPress affect the speed of a website? Do you think it's worth replacing all strings with gettext inside a theme, even if it will only be used on a single, english website?
|
If you know that you or the client will NEVER need to be translated there is no need to replace all the strings within your theme with gettext. Regarding the performance issue I found a benchmark comparing the 3 gettex methods. It also compared using the default local vs a different local and the differences were negligible which leads me to the conclusion that that you do take a performance hit when replacing all your strings with gettext. Benchmarks
|
Should we localize custom-made themes / plugins?
|
wordpress
|
I know there are plugins out there for integrating the user base & sign-up, but are there any for using PHPlist to automatically send out newsletters of new posts? I'm really trying to avoid a from-scratch solution here, though if nothing is 'ready made' I'd appreciate any pointers or head starts ;)
|
Don't know of a plugin that does that but if you take a look at WP PHPList plugin or more specifically the way it Interacts with phplist using PHP CURL, it logs in to phplist as admin and save cookie using <code> CURLOPT_COOKIEFILE </code> and then simulates a post to subscriber form. So maybe going in that route you can do the same and simulate a post to send mail form. then all that is left is to hook you function to these hooks: <code> add_action('new_to_publish', 'send_new_post_mail'); add_action('draft_to_publish', 'send_new_post_mail'); add_action('pending_to_publish', 'send_new_post_mail'); add_action('private_to_publish', 'send_new_post_mail'); add_action('future_to_publish', 'send_new_post_mail'); </code> I know its not a complete solution but should give you a jump start.
|
PHPlist & new posts notification?
|
wordpress
|
I construction of a administrative back office inside the wordpress theme for running our travel company, monitoring users, bookings and payments, it has come to my attention that it might be better served and more secure if such an area were in face a desktop application or offline webpage that connected to the internet inly to get the date. So how would one connect to wordpress from html/php pages sitting on the desktops of relevant computers? And is that a sensible idea or not? Many Thanks,
|
I'm curious how/where you got the impression that desktop apps are more secure than the WP admin. For better security, you can enable SSL for the normal WP admin web interface, by adding this line to wp-config.php: <code> define('FORCE_SSL_ADMIN', true); </code> More info here: http://codex.wordpress.org/Administration_Over_SSL
|
Building a Wordpress App
|
wordpress
|
I have customized my login screen with a logo using html{background:#E2DEAF url(.../images/login_logo.jpg) center top no-repeat;} because it is so wide. Usually would not tie something to the HTML element. works great BUT... it also shows up in the admin area. Anyway to prevent this? I only want it on the login.
|
Try selecting login body class instead of adding background to html tag. <code> body.login { background:#E2DEAF url(.../images/login_logo.jpg); } </code> You could also play with .page (pages only), .logged-in (logged users) and so forth :) Hope it helps.
|
Background image in login showing in admin area
|
wordpress
|
hey guys, I couldn't find anything on the web. Is it possible to have custom template for the image attachement page. I wonder if it is possible to add a navigation to the image attachement page so people can easily navigate through a gallery. Maybe it's even possible to add comments to each image? edit: Moreover is it also possible to query if I'm currently on an attachement page? E.g. for breadcrumbs I want to insert something like "home > back to post > current_image.jpg" edit/update: <code> function breadcrumbs() { if (!is_home()) { echo "<a href='" . get_bloginfo('home') . "' title='Home'>Home</a> &rang; "; if (is_category()) { $category = get_the_category(); echo $category[0]->cat_name; } else if (is_single()) { the_category('title_li='); echo " &rang; "; the_title(); } else if (is_page()) { $ancestors = get_post_ancestors($post); // echo ancestors foreach($ancestors as $id) { echo "<a href='" . get_permalink( $id ) . "' title='" . get_the_title( $id ) . "'>" . get_the_title( $id ) . "</a> &rang; "; } } else if (is_tag()) { global $wp_query; $tag = get_term( $wp_query->queried_object_id, 'post_tag'); echo "Tag &rang; " . $tag->name; } else if (is_search()) { echo " Searchresults &rang; " . get_search_query(); } else if (is_404()) { echo "Not found"; //} else if ( is_attachment() ) { } else if ($post->post_type == 'attachment') { //echo "<a href='" . get_permalink() . "'>" . get_the_title() . "</a>"; echo "doesn't work?"; } } } </code>
|
WordPress supports several types of attachment templates. The function <code> get_attachment_template </code> in <code> wp-includes/theme.php </code> provides this support; it is called in <code> wp-includes/template-redirect.php </code> . If your theme includes <code> attachment.php </code> all of your attachments will be rendered with that template. If your theme also includes <code> image.php </code> then all of your images will use that template as long as they have a post_mime_type of <code> image/* </code> . It is certainly possible to add gallery navigation. See <code> wp-content/themes/twentyten/loop-attachment.php </code> which uses functions <code> previous_image_link </code> and <code> next_image_link </code> . Twentyten's attachment template does call <code> comments_template </code> so you can collect comments on each photo. You just have to make sure your post links to the attachment pages and not directly to the images. You can call <code> is_attachment </code> to determine whether the queried object is an attachment.
|
page template for attachement page?
|
wordpress
|
Why isit that WordPress sometimes add a number to my slug even if I explicitly set it. Like if I set slug to be 'about' I get 'about-2'. I want the slug to be correct so I can style using CSS easily. Or is there a better way?
|
WordPress appends a number to your slug when the database already contains a duplicate slug. It will append the number even if the duplicate post or page has been moved to the trash. The URL Routing system is one of the weaknesses of WordPress. stackexchange-url ("Mike Schinkel") made a very good proposal to evolve the re write engine on trac but the ticket was closed as "wont fix"
|
Why does WordPress append numbers to page slugs sometimes? How to reliably style based on page
|
wordpress
|
How might I have custom markup for my menus, like I want to give menu items something like <code> id="menuitem-postname" </code> how might I do that?
|
The only way that I could think to do this would be to add a filter to <code> wp_nav_menu_items </code> . Here is the code that I got to work (just add it to your themes functions.php file): <code> add_filter('wp_nav_menu_items', 'my_id_name_nav', 10, 2); function my_id_name_nav($items,$args) { if( $args->theme_location == 'primary' ) { preg_match_all('/<li id="menu-item-([0-9]+)"([^>]+)>\s*<a href="([^"]+)">([^<]+)<\/a><\/li>/i', $items, $matches); $newItems = array(); for($i=0; $i<count($matches[0]); $i++){ $short = explode('/', $matches[3][$i]); $short = $short[count($short) - 2]; // if there is no trailing slash, subtract 1 instead of 2 array_push($newItems, '<li id="menu-item-'. $short .'"'. $matches[2][$i] .'><a href="'. $matches[3][$i] .'">'. $matches[4][$i] .'</a></li>'); } return implode('', $newItems); } else { return $items; } } </code> It uses the last part of the url to create the page name for the id. So menu-item-2 for http://yoursite.com/page1/page2/ would become menu-item-page2. The <code> if( $args->theme_location == 'primary' ) </code> is for targeting a specific menu. If you want to do this for all menus just remove the if else statement.
|
Custom markup with wp_nav_menu based on pages
|
wordpress
|
I have a new question, how can I limit the amount of posts coming out of this query? I only need 7 <code> <?php $newsposts = new WP_Query('cat=restaurant'); if ( is_front_page()) { echo '<h3 class="member-review">Latest Restaurants</h3> <div id="extra">'; if ($newsposts->have_posts()) : while ($newsposts->have_posts()) : $newsposts->the_post(); echo '<div class="reslogo"><img src="'.catch_that_image().'"/></div>'; endwhile; endif; echo '</div>'; } ?> </code> I tried to put: <code> ('cat=restaurants'.'limit=7') </code> but she no work. How did i go wrong? any help would be appreciated
|
It should be: <code> $newsposts = new WP_Query('cat=restaurant&posts_per_page=7'); </code> Another way to write it (helps readability with larger queries) would be: <code> $newsposts = new WP_Query(array( 'cat' => 'restaurant', 'posts_per_page' => 7, )); </code> See <code> WP_Query </code> in Codex for description of available parameters. PS would be good practice to add <code> wp_reset_postdata() </code> at the end. You are (correctly) not modifying main query, but you do change global <code> $post </code> variable with this loop.
|
How to limit the posts
|
wordpress
|
I'm creating common "Single Tag Page" for different Post Types. I'm using next code: <code> $loop = new WP_Query( array( 'post_type' => 'any', 'tag' => single_term_title( '', false ), 'posts_per_page' => 10 ) ); while ( $loop->have_posts() ) : $loop->the_post(); ?> <div class="entry-content"> <?php the_excerpt(); ?> </div><!-- .entry-content --> <?php endwhile; // End the loop. ?> </code> It works fine until there is no taxonomy terms conflict. For example: If I have Category & Tag names - "Videos" , Category will have slug - "/videos" & Tag "/videos-2" . In case when slug isn't the same as taxonomy name above code does not working. I need an alternative function for single_term_title() , something like "single_term_slug()" . Any ideas? P.S. I was thinking about " get_term_by() " function, but I didn't had luck to adopt it to the code above. Updated: I've posted my code below.
|
Thank you guys for such quick response. Much appreciated! Here is code for "global" Tags page (displaying terms of default 'post_tag' taxonomy): <code> <?php $term_slug = get_queried_object()->slug; if ( !$term_slug ) return; else $loop = new WP_Query( array( 'post_type' => 'any', 'tag' => $term_slug, 'posts_per_page' => 10 ) ); while ( $loop->have_posts() ) : $loop->the_post(); ?> <div class="entry-content"> <?php the_excerpt(); ?> </div><!-- .entry-content --> <?php endwhile; // End the loop. ?> </code> And the next code example is for custom taxonomy query (displaying terms of custom taxonomy): <code> <?php //http://codex.wordpress.org/Function_Reference/WP_Query#Taxonomy_Parameters $term_slug = get_queried_object()->slug; if ( !$term_slug ) return; else $args = array( 'tax_query' => array( array( 'taxonomy' => 'gallery_category', 'field' => 'slug', 'terms' => $term_slug, 'posts_per_page' => 10 ) ) ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); ?> <div class="entry-content"> <?php the_excerpt(); ?> </div><!-- .entry-content --> <?php endwhile; // End the loop. ?> </code>
|
Retrieve single term slug
|
wordpress
|
Ok, maybe it a far fetch question, and a question about depersonalisation of something into something else, but let try. One on my client want a easy file bin for his client to go get the public HR file for publicity. The main company have the HR pdf and some newspaper or local advertising need it. Instead of sending those file by email, CD or free FTP like "senduit.com" a site will be created. A bunch of folder, with a bunch of file. Let say Winter 2010 AD french ad 8.5 x 11 english ad 8.5 x 11 Summer 2011 AD french poster English poster and so on, understand the concept ? So what will be the best plugin set or system for that... wordpress seem fit to that, but it's sont OUT OF THE BOX as this.. system should be secure, but's that just adding a password page.. that simple... What will be your solution ?
|
Perhaps WP-Filebase would be a suitable plugin for you.
|
FTP file manager AS wordpress site
|
wordpress
|
I've asked a similar question before: stackexchange-url ("How to create thumbnails with a fixed width, so all of them will have the same width?") But... this one is related, but different. Please bear with me. Right now: if you insert an image in a post as a thumbnail by the media-library, you can choose between 4 different sizes: thumbnail, medium, big and actual size. This is fine. However: the dimensions of the thumbnail are determined by whether the image is landscape or portrait. You can set a maximum width or height in your media-settings. Maximum 300 width and maximum 300 height, for instance, will make a landscape image 300px width and a portrait image 300px height. So it won't be always 300px wide. Only if it's a landscape image. Please correct me, if I'm mistaken, but this is what I've encountered so far. The point: my client used to work with movable type, but decided to switch to wp. In mt, however, you could set a maximum width of a thumbnail, so that a thumbnail would be always this width, regardless of it being portrait or landscape. He wanted to have all of his thumbnails the same width, regardless of its orientation. This is not compatible with the way wp works, since the width will depend on the image's orientation. Question: how to make wp work like my client wants (ie: to set all the thumbnails the same width, whether landscape or portrait) And yes, the question is very similar to the one I referred to in the beginning, but that one was concerned with post-thumbnails which would be always the same size and this fixed width could be set within templates. In this case this is different: images are inserted in posts and the media-library determines the size. Not sure if I made myself clear. If I have: anyone has a solution? Be it a plugin (haven't found one yet) or a hack. If I haven't: shoot me and I'll try to clarify. Tnx!
|
You can set a maximum width for all image sizes and WordPress will crop portrait and landscape oriented images to that same width. In your media settings set the width field and leave the height field blank. When you upload a landscape oriented image the size will never go past the max width of 300px and the height will be proportionate . . When you upload a portrait orientated image the max width will still be 300px. . When the post or page is displayed both images will line up and be the same width:
|
media-library: how to insert thumbnails with a fixed width, regardless of landscape/portrait orientation
|
wordpress
|
I need to display images and other content in the sidebar depending on a page. Pages are added dynamically and information that need to appear in the sidebar is different for each page. So I can't predict what will go where. So the idea was is to have a page's content as usual (with all the neccessary shortcodes) and then at the end of page content have a shortcode with all the info that needs to appear in the sidebar for that page. Original question: displaying shortcodes selectively (suppress in the main content and instead display in a sidebar) I was wondering if it's possible to display shortcodes "selectively". For example, a specific shortcode, let's call it <code> [sc] </code> , is specified within a page content. Now, when displaying that page's content I would like to suppress that specific <code> [sc] </code> shortcode, but instead display it from the sidebar for that page. Content of a page will have other shortcodes. I only want to do selectively display the specific <code> [sc] </code> shortcode and process others as usual - i.e. other shortcodes will be processed within the page's content. Is that possible to do? And how?
|
A shortcode handler doesn't have to return anything, it can just modify a global variable that you later read in your sidebar widget. If your sidebar is displayed after your post content (most likely if it's a right sidebar), you can do this without any problem. If your sidebar is displayed before the post content it is more complicated: you have to start output buffering when your widget is called, wait until the rest of the page is displayed, and then do something with the shortcode content and flush the output buffer. A simple "proof of concept" that displays the shortcode content not in the post but in the footer: <code> $wpse13925_shortcode_content = array(); add_shortcode( '13925', 'wpse13925_shortcode' ); function wpse13925_shortcode( $shortcode_attr, $shortcode_content ) { $GLOBALS['wpse13925_shortcode_content'][] = $shortcode_content; return ''; } add_action( 'wp_footer', 'wpse13925_footer' ); function wpse13925_footer() { var_dump( $GLOBALS['wpse13925_shortcode_content'] ); } </code>
|
Display post shortcode content in the sidebar?
|
wordpress
|
Is there a plugin or some php code to do this: I want to disable some categories from the category box on the add/edit message page. I don't want to delete the categories and I want to leave the disabled categories to the previously assigned posts.
|
I have solved the problem myself, but it is not a pretty one. With the function attached to the <code> add_meta_boxes </code> action hook, I change the callback function that builds the category box. It replaces this function with the customized function <code> post_categories_meta_box_custom </code> . <code> post_categories_meta_box_custom </code> is a copy of <code> post_categories_meta_box </code> from <code> wp-admin/includes/meta-boxes.php </code> . With the help of simple-html-dom the <code> <li>...</li> </code> with the specified id is removed. <code> <?php function terms_meta_boxes($post_type, $post) { global $wp_meta_boxes; foreach ($wp_meta_boxes[$post_type] as $context => $priorities) { foreach ($priorities as $priority => $ids) { foreach ($ids as $id => $meta_box) { $tax = get_taxonomy( $meta_box['args']['taxonomy'] ); if ( $tax->hierarchical ) { $wp_meta_boxes[$post_type][$context][$priority][$id]['callback'] = 'post_categories_meta_box_custom'; } } } } } add_action('add_meta_boxes', 'terms_meta_boxes', 10, 2); /** * Custom function to display post categories form fields. * Original wp function: post_categories_meta_box. * * @param object $post */ function post_categories_meta_box_custom( $post, $box ) { $defaults = array('taxonomy' => 'category'); if ( !isset($box['args']) || !is_array($box['args']) ) $args = array(); else $args = $box['args']; extract( wp_parse_args($args, $defaults), EXTR_SKIP ); $tax = get_taxonomy($taxonomy); ?> <div id="taxonomy-<?php echo $taxonomy; ?>" class="categorydiv"> <ul id="<?php echo $taxonomy; ?>-tabs" class="category-tabs"> <li class="tabs"><a href="#<?php echo $taxonomy; ?>-all" tabindex="3"><?php echo $tax->labels->all_items; ?></a></li> <li class="hide-if-no-js"><a href="#<?php echo $taxonomy; ?>-pop" tabindex="3"><?php _e( 'Most Used' ); ?></a></li> </ul> <div id="<?php echo $taxonomy; ?>-pop" class="tabs-panel" style="display: none;"> <ul id="<?php echo $taxonomy; ?>checklist-pop" class="categorychecklist form-no-clear" > <?php $popular_ids = wp_popular_terms_checklist($taxonomy); ?> </ul> </div> <div id="<?php echo $taxonomy; ?>-all" class="tabs-panel"> <?php $name = ( $taxonomy == 'category' ) ? 'post_category' : 'tax_input[' . $taxonomy . ']'; echo "<input type='hidden' name='{$name}[]' value='0' />"; // Allows for an empty term set to be sent. 0 is an invalid Term ID and will be ignored by empty() checks. ?> <ul id="<?php echo $taxonomy; ?>checklist" class="list:<?php echo $taxonomy?> categorychecklist form-no-clear"> <?php ob_start(); wp_terms_checklist($post->ID, array( 'taxonomy' => $taxonomy, 'popular_cats' => $popular_ids ) ); $html_checklist = str_get_html(ob_get_clean()); $disabled_cats = get_option('disabled_cats', array()); foreach ($disabled_cats[$taxonomy] as $cat) { $html_checklist->find('li#category-' . $cat, 0)->outertext = ''; } echo $html_checklist->save(); ?> </ul> </div> <?php if ( current_user_can($tax->cap->edit_terms) ) : ?> <div id="<?php echo $taxonomy; ?>-adder" class="wp-hidden-children"> <h4> <a id="<?php echo $taxonomy; ?>-add-toggle" href="#<?php echo $taxonomy; ?>-add" class="hide-if-no-js" tabindex="3"> <?php /* translators: %s: add new taxonomy label */ printf( __( '+ %s' ), $tax->labels->add_new_item ); ?> </a> </h4> <p id="<?php echo $taxonomy; ?>-add" class="category-add wp-hidden-child"> <label class="screen-reader-text" for="new<?php echo $taxonomy; ?>"><?php echo $tax->labels->add_new_item; ?></label> <input type="text" name="new<?php echo $taxonomy; ?>" id="new<?php echo $taxonomy; ?>" class="form-required form-input-tip" value="<?php echo esc_attr( $tax->labels->new_item_name ); ?>" tabindex="3" aria-required="true"/> <label class="screen-reader-text" for="new<?php echo $taxonomy; ?>_parent"> <?php echo $tax->labels->parent_item_colon; ?> </label> <?php wp_dropdown_categories( array( 'taxonomy' => $taxonomy, 'hide_empty' => 0, 'name' => 'new'.$taxonomy.'_parent', 'orderby' => 'name', 'hierarchical' => 1, 'show_option_none' => '&mdash; ' . $tax->labels->parent_item . ' &mdash;', 'tab_index' => 3 ) ); ?> <input type="button" id="<?php echo $taxonomy; ?>-add-submit" class="add:<?php echo $taxonomy ?>checklist:<?php echo $taxonomy ?>-add button category-add-sumbit" value="<?php echo esc_attr( $tax->labels->add_new_item ); ?>" tabindex="3" /> <?php wp_nonce_field( 'add-'.$taxonomy, '_ajax_nonce-add-'.$taxonomy, false ); ?> <span id="<?php echo $taxonomy; ?>-ajax-response"></span> </p> </div> <?php endif; ?> </div> <?php } ?> </code>
|
How to disable category without deleting?
|
wordpress
|
I am working on a function that displays all authors but it appears I am doing something wrong the HTML within does not display until the bottom of the page separate from the output. <code> /* Add shortcode to display authors */ function all_authors() { global $wpdb; $authors = $wpdb->get_results("SELECT ID, user_nicename from $wpdb->users where ID not in(1)"); $retval = '<div id="author_list"><ul>'; foreach($authors as $author) { $retval .= '<li>'; if(userphoto_exists($author->ID)) echo userphoto($author->ID); else $retval .= get_avatar($author->ID, 96); $retval .= '<h6>'.the_author_meta('display_name', $author->ID).', '.the_author_meta('tagline', $author->ID); $retval .= '</h6><p>'.the_author_meta('description', $author->ID).'</p><p><strong>'.the_author_meta('phone', $author->ID); $retval .= ' | <a href="'.the_author_meta('user_url', $author->ID).'" target="_blank">'.the_author_meta('user_url', $author->ID).'</a></strong></p></li>'; } $retval .= '</ul></div>'; return $retval; } add_shortcode('myauthorbox', 'all_authors'); </code>
|
<code> the_author_meta() </code> is display function, it echoes the result to screen right where it's called. To concatenate with string you need to use function that returns result - <code> get_the_author_meta() </code> .
|
Shortcode not displaying HTML within the function
|
wordpress
|
This should be easy. I need to query to display one page in a tab. Just pull one page by one query, but I'm doing something (maybe lots) wrong here: Edit: Hah. I forgot <code> the_content </code> It works now. <code> <?php $the_query = new WP_Query; $the_query->query ('pagename=about' ); while ($the_query->have_posts()) : $the_query->the_post(); ?> <?php the_content(); ?> //forgot this <?php endwhile; ?> </code>
|
Hah. I forgot <code> <?php the_content(); ?> </code>
|
Why doesn't this page query work?
|
wordpress
|
How does one go about locking down transient API requests for multiple threading? Has anything done some benchmarking, just how much can the transient API handle for multiple concurrent requests? It seems like it might cause some severe bottlenecks if not managed properly. Also how would one go about forcing the transient API using WP's built in cron? For instance I have a transient firing on page load that I gather statistics from ( another seperate function) but if a page isn't visited then the transient is not updated, how would you loop through all the pages/posts using transient API to force an update? The cron might also be effective in dealing with my first question to avoid multiple threading, too many requests and performance. I have been wondering about this and recently a core dev alluded to it on a blog post, the Transient API is so simple to use but seems to lack some documentation for advanced management. Any insights would be really appreciated.
|
How does one go about locking down transient API requests for multiple threading? Has anything done some benchmarking, just how much can the transient API handle for multiple concurrent requests? Under normal circumstances Transients API is essentially thin wrapper on top of Options API. The difference is that (unlike plain options) transients might make use of object cache, if plugin that provides such functionality is installed. So answer to this - transients perform as well as your database does, unless you change them to use another type of storage. Then it's as good as that storage. Also how would one go about forcing the transient API using WP's built in cron? For instance I have a transient firing on page load that I gather statistics from ( another seperate function) but if a page isn't visited then the transient is not updated, how would you loop through all the pages/posts using transient API to force an update? I am not sure what you mean here. Transients are merely storage mechanism. They are used to store and retrieve [expiring] data. Anything other than that you will need to implement in your own code.
|
Any insights into Transient API locking, cron and threading?
|
wordpress
|
<code> <?php echo do_shortcode('[mingleforum]'); ?> </code> inserts the mingle forum into my content! is it possible to use add_filter() on that?
|
You can change your code to this: <code> <?php $shortcode = do_shortcode('[mingleforum]'); echo apply_filters('my_new_filter',$shortcode); ?> </code> and then you can interact with that filter <code> add_filter('my_new_filter','my_new_filter_callback'); function my_new_filter_callback($shortcode){ //to stuff here return $shortcode; } </code>
|
adding a filter to a shortcode?
|
wordpress
|
I've got a default main menu: <code> wp_nav_menu(); </code> But it gives a list of links in a form: <code> (...) <a href="link" title="PageName">PageName</a> (...) </code> The very important question is, how to force WP to display it like: <code> (...) <a href="link">PageName</a> (...) </code> I don't like the yellow boxes appearing every time I hover anything in menu. I know it's possible, because I've seen it working, but no idea how? Filters maybe? Any ideas?
|
The title is an accessibility attribute that helps users with screen readers. It is part of the recommended WC3 standard for navigation items. Just think about that before you decide to eliminate it because you find it annoying. Rather than modifying the PHP code, you could think about removing it after it's loaded. It's very easy to do this with jQuery. First, add this to your <code> functions.php </code> file: wp_enqueue_script('jquery'); Next, in your <code> site.js </code> file, add this code: <script type="text/javascript" > jQuery(document).ready(function($){ $('.nav li a').removeAttr('title'); } </script> Again, I don't really recommend doing this, but this is how to accomplish it.
|
Main menu - get rid of titles?
|
wordpress
|
I'm looking for a plugin that will allow the user to upload files, maybe 4-10 that can be used on the homepage as part of a slideshow. I can code the slideshow part myself, if necessary, but the thing I'm interested in is a way for the user to select / upload the photos. It would be excellent if they were integrated with Wordpress' media manager just like other uploads. Thanks!
|
jQuery Cycle and Cycle Lite are very flexible and very easy to use. Most WordPress slideshow plugins either don't do exactly what you need or they try to do everything and are overly complicated with options and features. The solution Build the slideshow feature into your theme template or code your own plugin. To make it easy and intuitive for the user I would create a "Featured Content" custom post type that only supports a featured image (thumbnail) and the excerpt if you want to add a caption to each image. Register your custom post type and for the supports argument use: <code> 'supports' => array('thumbnail','excerpt',) </code> Enqueue your scripts in functions.php <code> <?php add_action( 'init', 'c3m_get_the_js' ); function c3m_get_the_js() { wp_register_script( 'jquery.cycle', get_bloginfo('template_directory'). '/path_to_your_js/jquery.cycle.lite.1.1.min.js', array('jquery'), TRUE); wp_enqueue_script('jquery.cycle' ); wp_enqueue_script( 'custom', get_bloginfo('template_directory'). '/path_to_your_js/c3m_functions.js', array('jquery.cycle'), TRUE); } ?> </code> Set your "featured image" size in functions.php <code> add_image_size( 'featured', 747, 285, true ); </code> Set up the the template to display your slideshow <code> <div id="home-slider"> <div class="cycle-nav"> <a id="prev2" href="#">«Prev</a> <a id="next2" href="#">Next»</a> </div> <ul id="cycle" class="pics"> <?php $i = 1; global $wp_query; $custom_query = array( 'post_type' => 'featured_content', 'posts_per_page' => -1 ); if ( $custom_query ) query_posts( $custom_query ); $more = 0; ?> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <li class="cycle-item slide-<?php echo $i; ?>"> <?php the_post_thumbnail('featured'); ?> <div class="excerpt"> <?php echo get_the_content('<span class="more">more &raquo;</span>'); //Use this if you want text with your images ?> </div> </li> <?php $i++; endwhile; endif; ?> <?php wp_reset_query(); ?> </ul> </div> <!-- /home-slider --> </code> Add your jQuery Cycle settings to your custom.js file <code> jQuery.noConflict(); jQuery(document).ready(function($) { jQuery('ul#cycle').cycle({ timeout: 9000, speed: 1500, delay: 2000, prev: '#prev2', next: '#next2' }); }); </code> Add some css <code> #home-slider { width:735px; overflow:hidden; height:280px; float:right; position:relative; margin-right:0; display:inline-block } a#prev2 { position:absolute; width:31px; height:32px; text-indent:-999em; z-index:100; background-position:0 0; background-image:url(images/cycle-nav.png); top:185px; box-shadow:1px 1px 2px rgba(2,2,2,0.3); -moz-box-shadow:1px 1px 2px rgba(2,2,2,0.3); -webkit-box-shadow:1px 1px 2px rgba(2,2,2,0.3) } a#prev2:hover { background-position:0px -32px } a#next2 { position:absolute; right:0px; width:31px; height:31px; display:block; z-index:100; top:185px; background-position:31px 0px; background-image:url(images/cycle-nav.png); overflow:hidden; text-indent:-999em; box-shadow:1px 1px 2px rgba(2,2,2,.3); -moz-box-shadow:1px 1px 2px rgba(2,2,2,0.3); -webkit-box-shadow:1px 1px 2px rgba(2,2,2,0.3) } a#next2:hover { background-position:31px -32px } ul#cycle { margin:0; padding:0; list-style:none } ul#cycle .excerpt { width:700px; height:82px; background: rgb(0, 0, 0); background:rgba(0,0,0,.5); position:absolute; bottom:0; padding:10px 20px 10px 25px; overflow:hidden } </code> The UI The Slider on the front end
|
What plugin can I use to create a list / slideshow of featured images?
|
wordpress
|
The question is pretty simple, but it's complex in fact. I have implemented custom sidebars for each post/page function in my blog. It looks like: <code> <div id="<?php echo get_option('sidebar-layout');" ?> <div id="content"> Some content [myshortcode] </div> <div id="sidebar"> Sidebar </div> </div> </code> sidebar-layout option can have three values - left, right and none. And none is default. They are all set via metabox under post/page. The biggest problem here is that when user chooses left - the first div gets "left" class and everything else is based on this ID, eg. <code> #left #content { style; } </code> And when he takes "right" then different style is applied: <code> #right #content { another style; } </code> So my "myshortcode" should basically change parents DIV id. Any ideas how to achieve that? I believe my shortcode will be executed AFTER the div ID.
|
Use this code to echo your div's ID <code> <?php $sidebar_layout = get_post_meta($post->ID, 'sidebar-layout', $single = true); ?> <div id="<?php echo $sidebar_layout ?>"> <div class="content"> ... </div> <div class="sidebar"> ... </div> </div> </code> If you want to apply styles according to the selection the user has made then change your style sheet as follows: <code> #left .content{ ... } #left .sidebar{ ... } #right .content{ ... } #right .sidebar{ ... } #none .content{ ... } #none .sidebar{ ... } </code> I hope this helps.
|
Hide/disable sidebar using shortcode?
|
wordpress
|
I've got several custom image sizes for my blog. One of these is setup as <code> add_image_size( 'slide', 640, 290, true ); </code> . These are used in a header slideshow. My problem is I've upped the dimensions of this size after many of them were originally created, and many of the attached post images are too small to be cropped to these new values (i.e. not even 640px in the first place). So when I call up images of this size, many of them are of the old dimensions (e.g. <code> s:5:"slide";a:4:{s:4:"file";s:52:"6a00d8341c630a53ef011570180a91970b-800wi-300x290.jpg";s:5:"width";s:3:"300";s:6:"height";s:3:"290";} </code> . I can't use images that are this small, but no correctly sized image are overwriting these, as per above. The desired behavior is that no image would be stored for <code> size </code> slide instead of the old, small ones. How can I delete these image entries in _wp_attachment_metadata? Do I do delete everything in the <code> sizes </code> sub-array and regenerate everything?
|
Not from personal experience (I don't use WP image management much), but I believe Regenerate Thumbnails plugin is usually recommended for rebuilding thumbnails.
|
How to delete outdated, wrongly sized images in _wp_attachment_metadata?
|
wordpress
|
I've used Justin Tadlock's great function for category specific custom post templates many times, where you can use single-cat-id.php for single posts belonging to a specific category. I just ran into a problem though working on a new site that needs to use the single-{posttype} template for a custom post type. The function seems to prevent the custom posts from using single-{posttype} template. Here's the applicable code: <code> /* Define a constant path to our single template folder */ define(SINGLE_PATH, TEMPLATEPATH . '/single'); /* Filter the single_template with our custom function*/ add_filter('single_template', 'my_single_template'); /* Single template function which will choose our template*/ function my_single_template($single) { global $wp_query, $post; /* Checks for single template by category. Check by category slug and ID */ foreach((array)get_the_category() as $cat) : if(file_exists(SINGLE_PATH . '/single-cat-' . $cat->slug . '.php')) return SINGLE_PATH . '/single-cat-' . $cat->slug . '.php'; elseif(file_exists(SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php')) return SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php'; endforeach; /*Checks for default single post files within the single folder */ if(file_exists(SINGLE_PATH . '/single.php')) return SINGLE_PATH . '/single.php'; elseif(file_exists(SINGLE_PATH . '/default.php')) return SINGLE_PATH . '/default.php'; return $single; } </code> Any thoughts on how to modify the following code to allow both the original function of single-cat-id as well as single-{posttype} ?
|
You can check for your post type single-{post-type}.php first try this: <code> /* Define a constant path to our single template folder */ define(SINGLE_PATH, TEMPLATEPATH . '/single'); /* Filter the single_template with our custom function*/ add_filter('single_template', 'my_single_template'); /* Single template function which will choose our template*/ function my_single_template($single) { global $wp_query, $post; /* Checks for single template by post type */ if ($post->post_type == "POST TYPE NAME"){ if(file_exists(SINGLE_PATH . '/single-' . $post->post_type . '.php')) return SINGLE_PATH . '/single-' . $post->post_type . '.php'; } /* Checks for single template by category. Check by category slug and ID */ foreach((array)get_the_category() as $cat) : if(file_exists(SINGLE_PATH . '/single-cat-' . $cat->slug . '.php')) return SINGLE_PATH . '/single-cat-' . $cat->slug . '.php'; elseif(file_exists(SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php')) return SINGLE_PATH . '/single-cat-' . $cat->term_id . '.php'; endforeach; /*Checks for default single post files within the single folder */ if(file_exists(SINGLE_PATH . '/single.php')) return SINGLE_PATH . '/single.php'; elseif(file_exists(SINGLE_PATH . '/default.php')) return SINGLE_PATH . '/default.php'; return $single; } </code> and just replace "POST TYPE NAME" with your custom post type name.
|
Conflict in function to allow single post template based on category
|
wordpress
|
I always find myself creating posts every time to test layout or design. For example, I create stuff like: Content 1 Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. 6 times. Is there a fast way of copy pasting posts, duplicating them or auto-generating them, perhaps?
|
I use Demo Data Creator plugin with it you can create and set: Number of users to create Number of blogs per user (for WPMU/MultiSite) Whether users must have a blog Number of categories in each blog Number of posts in each blog Number of paragraphs in each blog post Number of pages in each blog Number of top-level pages Number of levels to nest pages Number of comments per post for each blog Number of links in blogroll for each blog
|
Is there any way of copy/pasting, duplicating, or auto-generating posts for fast testing?
|
wordpress
|
I've written a plugin that allows users to add information in the database. It runs well but I can't translate the information using WPML. This is a simple example of the problem: $message = 'test'; // here I get the information of the DB __($message, 'my-plugin'); Is there a way to workaround this problem? I don't know if we can use a variable instead of a string to translate. When I analize the widget in the Admin panel it don't show the string to translate. This example works in WPML because is a string: __('test', 'my-plugin'); Thanks in advance.
|
If you want to have variables in your text to be translated the usual way would be with string formatting like so: <code> <?php printf(__("text %s text2."), $message); ?> </code> with integers: <code> <?php printf(__("text %d text2."), $count); ?> </code> with more then one placeholders: <code> <?php printf(__("text %1$s text2 %2$S."), $message, $message2); ?> </code> but the variable it self will not be translated in no way. WPML doesn't run the code before <code> __(); </code> or <code> _e(); </code> function it only search the files for them, and that is why when you write something like this: <code> $message = 'test'; // here I get the information of the DB __($message, 'my-plugin'); </code> WPML only sees <code> __($message, 'my-plugin'); </code> where $message is empty.
|
Translate database content using __($message) function
|
wordpress
|
Hiya Guys! so I need some help with this: <code> <?php $newsposts = new WP_Query('cat=restaurant'); if ( is_front_page()) { echo '<h3 class="member-review">Latest Restaurants</h3> <div id="extra">if ($newsposts->have_posts()) : while ($newsposts->have_posts()) : $newsposts->the_post(); <div class="reslogo"><img src="'echo catch_that_image()' /></div> endwhile, endif; </div>'; } ?> </code> What I'm trying to do here is have an image slider of first post images (from restaurant category) display at the bottom of the page. I use DIVs to control placement/ style but I really need help with my PHP syntax ... I just cant figure it out... Any help would be greatly appreciated! Cheers
|
you can't run code inside quote since php treats it as string, try this: <code> <?php $newsposts = new WP_Query('cat=restaurant'); if ( is_front_page()) { echo '<h3 class="member-review">Latest Restaurants</h3> <div id="extra">'; if ($newsposts->have_posts()) : while ($newsposts->have_posts()) : $newsposts->the_post(); echo '<div class="reslogo"><img src="'.catch_that_image().'"/></div>'; endwhile, endif; echo '</div>'; } ?> </code>
|
PHP nested If statement syntax
|
wordpress
|
I have custom post type and I want to have a menu where I combine category or categories from default Wordpress post type and from my custom post type. Let's say I have these categories sport, books, movies, any in default post type sport, books, school, any in my custom post type can I have a menu link where I would display sport posts from both post types? sport, books posts from default post type and any from my custom post type?
|
What I would suggest in this situation is that you create a "CUSTOM QUERY" to query the posts. Set this custom query into a page, then use Appearance > Menu's to add the page into your menu structure. I hope this helps.
|
can I 'combine' categories as a menu item?
|
wordpress
|
I'm student web developer and I'd like to know the things I should know before venturing into WordPress. Where do I start?
|
Glad your taking the jump into wordpress, wordpress is an amazing platform for developers and non-developers alike, if you have knowledge of PHP, HTML, CSS (and jQuery in some instances) you will enjoy working with wordpress. A great place to start understanding wordpress would of-course be the wordpress website itself. http://codex.wordpress.org/Main_Page I hope this helps, for more specific tutorials and tips / tricks i find myself scouring google every-time i need something.
|
Where do I start from
|
wordpress
|
I just found the magnificent wp_insert_post function and have a few basic question about it. *For reference I used this on a multisite install for a number of blogs running theme_x. I simply wanted to add a page to each blog (without having to do it through WP Admin). This seems to have mostly-worked though I'm not sure I'm using it for its intended purpose? What happens if the specified page title already exists on several blogs? Does it a) terminate the function b)rename in typical WP fashion to "page-name-2" format, or c) something else? Should I remove the code from the theme template now that I have done what I needed to? I'd like to leave it in just incase more blogs are added which use this theme but I'm wondering if it creates unnecessary database overload (does it get run every page load)? The page doesn't appear anywhere in WP admin? Though all blogs using this theme do indeed resolve to the newly-added page like so ... URL/newly-added-page. This is fine for me in this instance, but it makes me think I'm not using the function "properly" (I kinda expected a new page in WP Admin also)
|
Wordpress just adds a new entry, the title is not unique, but there is a field guid which is. Permalinks do get an incremental number. Yes, you should remove it from your theme, you'd better write your own plugin for this kind of stuff. I don't totally understand what you mean, is there no menu entry in the admin? That's because it's not a plugin. Does it not show up in the theme editor? Then the file probably doesn't have an appropiate header, is not in the correct place or not correctly named.
|
Proper procedure for wp_insert_post?
|
wordpress
|
I try to save an option from the frontend but i can't find yet how to do it. So, the idea is to give the blog owner a simple form with a dropdown that can select a different stylesheet.css. I have build it for the wp-admin area and it works fine, but i want to do the same in the frontend, i have tried to include the wp-admin/options.php in the header but nothing, just errors, i post the form to "wp-admin/options.php" but it redirect me in the wp-admin/options page. here is the frontend form: <code> <form id="save-theme" name="save-theme" action="/wp-admin/options.php" method="post"> <select> <option>Select Theme</option> <option>Red</option> <option>Dark</option> <option>White</option> </select> <button name="update-options" type="submit">Save</button> <?php wp_nonce_field('update-options'); ?> </form> </code> thanks a lot!
|
You Do Not want to post /wp-admin/options.php from the front end , thats a bad idea and can cause problems. To updated Options from the frontend simply use update_option() and make sure you verify correctly. here is an example using your code with minor fixes: <code> <?php if (isset($_POST['stylesheet']) && isset($_POST['action']) && $_POST['action'] == "update_theme"){ if (wp_verify_nonce($_POST['theme_front_end'],'update-options')){ update_option('my_theme-style',$_POST['stylesheet']); }else{ ?><div class="error"><?php echo 'update failed'; ?></div><?php} } ?> <form id="save-theme" name="save-theme" action="" method="post"> <select name="stylesheet"> <?php $selected = get_option('my_theme-style'); <option>Select Theme</option> <option value="1" <?php if ($selected == 1) echo 'selected="selected"'; ?>>Red</option> <option value="2" <?php if ($selected == 2) echo 'selected="selected"'; ?>>Dark</option> <option value="3" <?php if ($selected == 3) echo 'selected="selected"'; ?>>White</option> </select> <?php wp_nonce_field('update-options','theme_front_end'); ?> <input type="hidden" name="action" value="update_theme"> <input type="submit" name="update-options" value="Save"> </form> </code> Now this assumes that the option key or name is my_theme-style.
|
Save Theme Options (options.php) From The Frontend
|
wordpress
|
Hey guys, I simply want to prevent the creation of empty paragraphs in my wordpress post. That happens quite often when trying to manually space content. I don't know why this doesn't take effect? <code> /*Remove empty paragraph tags from the_content*/ function removeEmptyParagraphs($content) { /*$pattern = "/<p[^>]*><\\/p[^>]*>/"; $content = preg_replace($pattern, '', $content);*/ $content = str_replace("<p></p>","",$content); return $content; } add_filter('the_content', 'removeEmptyParagraphs'); </code> edit/update: seems like the problem is this: <code> function qanda($content) { // filters for [q=some question] and [a=some answer] // wraps it inside of <div class="qanda"><div class="question"> </div><div class="answer"> </div></div> $content = preg_replace('/\[q=(.+?)].+?\[a=(.+?)]/is', '<div class="qanda"><div class="question">$1</div><div class="answer">$2</div></div>', $content); return $content; } add_filter('the_content', 'qanda'); </code> i did this function myself to filter for a kind of shortcode pattern in my posts and pages. Even though in my backend the post is completely done without paragraphs and unnecessary spacings the outcome looks like this: <code> <div class="entry"> <p></p> <div class="qanda">...</div> <p></p> <p></p> <div class="qanda">...</div> <p></p> <p></p> <div class="qanda">...</div> </div> </code> any idea where this empty p's come from?
|
WordPress will automatically insert <code> <p> </code> and <code> </p> </code> tags which separate content breaks within a post or page. If, for some reason, you want or need to remove these, you can use either of the following code snippets. To completely disable the wpautop filter, you can use: <code> remove_filter('the_content', 'wpautop'); </code> If you still want this to function try adding a later priority value to your filter something like: <code> add_filter('the_content', 'removeEmptyParagraphs',99999); </code>
|
remove empty paragraphs from the_content?
|
wordpress
|
I think my audience is more capable of answers each others' questions than I am. I need a system for them to do that and I'd like it to integrate with WP so I could use their existing usernames and accounts. Do you know of a good solution?
|
Have you heard of WP Answers ? It is a plugin that appears to do exactly what you need. There are also some themes out there that do what you're after; after a quick comparison, the Answers theme by Templatic appears to be one of the nicer ones.
|
Is there a good Q&A platform to integrate into WordPress?
|
wordpress
|
I have several virtual hosts setup, three of them pull files via SVN when needed(though only the trunk folder actually needs this), using SVN for other versions make for easy patch creation, or easy file replacement if i hack a core file. My question is whether i can checkin a plugin from directly inside the plugins directory? So take this plugin located in <code> wp-content/plugins/post-ui-tabs </code> for example. Can i use that folder to house my WordPress.org plugin or does my plugin's folder need to mimic the directory structure of the SVN, eg.. brances/ tags/ trunk/ UPDATE: Thanks for the feedback guys! All helpful in getting to understand local vs remote directory structure. I've got my plugin up in the repo now, see here. Post UI Tabs Direct answer to my question, was Yes, i can do commits directly from my plugins folder, i simply have a typical local structure of <code> wp-content/plugins/myplugin </code> which is just a checkout of <code> http://svn.wp-plugins.org/myplugin/trunk </code> . I commit directly to trunk, then when i want to push a new version, i branch onto a tag(do that directly in Tortoise) and update the readme.txt stable tag to reference the new tag, ie. the operation creates the remote <code> http://svn.wp-plugins.org/myplugin/tag/VER </code> with all my files, and makes that available to uses, whilst my local working copy remains on trunk(i'll blog about it in the future when i've had more practice). Easier then i thought!... thanks for all the advice guys.. all valuable pieces of information, Andy i felt your answer helped the most, so i'm giving you the accept, everyone else i still really appreciate your help, unfortunately i can only accept one answer... but thank you all the same.
|
I run a WordPress checkout of trunk, a branch, or a tag. This way I can switch WordPress versions easily: <code> svn sw http://svn.automattic.com/wordpress/trunk svn sw http://svn.automattic.com/wordpress/tags/3.1 </code> In <code> wp-content/plugins </code> I have a trunk checkout for each of my plugins: <code> cd wp-content/plugins svn co http://plugins.svn.wordpress.org/stats/trunk/ stats </code> I do my work on the stats plugin (updating the changelog in the readme), then I commit directly from there: <code> emacs stats.php readme.txt svn di stats.php readme.txt svn ci stats.php readme.txt -m "stats: fixed issue with SSL" </code> When it's time to push a new version, I copy from trunk to the new tag: <code> svn cp http://plugins.svn.wordpress.org/stats/trunk/ http://plugins.svn.wordpress.org/stats/tags/4.2.1/ -m "stats: tag 4.2.1" </code> Finally I bump the stable tag in the readme and commit that to trunk. <code> emacs readme.txt svn di readme.txt svn ci readme.txt -m "stats: bump stable tag to 4.2.1" </code> I do all of this in Linux or Mac. In my former life as a Windows user, I'd SSH (PuTTY) into a Linux box or (last resort) virtualize Linux.
|
Can i do plugin commits directly from a plugin folder inside an installation using the Trunk SVN
|
wordpress
|
I use paged and threaded comments with: 10 comments per page the last comment page first the newest comments first If there are 21 comments total, the first page only contain 1 comment - the newest. How do i get the newest 10 comments always showing on the first page? I'm using WordPress 3.0.3. Edit: Upgraded to 3.1, the problem still exists... Edit: Forgot to add the code I'm using. I use a callback for the listed comments, here goes: <code> function mytheme_comment($comment, $args, $depth) { $GLOBALS['comment'] = $comment; ?> <li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>"> <div id="comment-<?php comment_ID(); ?>" class="comment"> <?php if(function_exists('hkTC_comment_title')) hkTC_comment_title($comment->comment_ID,'<strong class="comment-title">','</strong>'); ?> <?php comment_text() ?> <span class="written-by"> Skrivet av: <?php $commentAuthID = get_comment(get_comment_ID())->user_id; echo the_author_meta('first_name',$commentAuthID)." "; echo the_author_meta('last_name',$commentAuthID); ?> <em>kl. <?php echo get_comment_time('H.i'); ?>, den <?php echo get_comment_date('j F Y'); ?></em> </span> <div class="reply"> <?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?> </div> </div> <?php } </code> The hkTC_comment_title function is from this plugin that I'm also using: http://wordpress.org/extend/plugins/hikari-title-comments/ But that shouldn't mess with the number of comments I think. Edit: This is my custom template used to display the page with the comments: http://123.writeboard.com/4x2m38ifvnkrct7l
|
This is indeed the default behavior of WordPress. The comments always stay on the same comment page, so if you show the last comment page first, that last comment page will not always have the "full" number of comments. The advantage of keeping a comment always on the same comment page is that the URL always stays the same, otherwise a comment can move to another page when new comments are added. But it's annoying, and I needed a workaround for this too. I found no (easy?) way to do this with WordPress hooks, so I sliced the comment array myself, by reading the <code> cpage </code> (comment page) query variable. Watch out with this variable, because WordPress will be so helpful to reverse it for you when you set the "first/last comment page first" to "last". This code goes in the <code> comments.php </code> theme file, because it reads the global variable <code> $comments </code> . I did not use a comment callback (it was very simple code), but you can still pass the newly sliced <code> $comments_to_display </code> array to <code> wp_list_comments() </code> as the second argument, it will use that instead of all comments then. I don't know how this will work with threaded comments (how do they work with "normal" paged comments?). <code> $comments_to_display = $comments; /* * Display the comments over pages, with the newest comments on the first page * Special in this code (not in WP by default) is that the first page will contain 5 comments, * and the final page can contain less comments. */ $comments_per_page = 5; // MAYBE: use get_option()? $comment_page = get_query_var( 'cpage' ); $comment_this_page_start = 0; $comment_this_page_count = $comments_per_page; $oldest_comment_page_count = count( $comments_to_display ) % $comments_per_page; if ( 0 == $oldest_comment_page_count ) { $oldest_comment_page_count = $comments_per_page; } if ( 1 == $comment_page ) { $comment_this_page_count = $oldest_comment_page_count; } else { $comment_this_page_start = $oldest_comment_page_count + ($comment_page - 2) * $comments_per_page; } $comments_to_display = array_slice( $comments_to_display, $comment_this_page_start, $comment_this_page_count ); // You probably want to array_reverse() $comments_to_display, currently it shows the oldest on top. // Then you should be able to pass $comments_to_display to wp_list_comments() and it will use your shorter array instead. </code>
|
Last comment page first with full number of comments?
|
wordpress
|
This has me stumped for a while already. Either I am missing something very obvious or something very not obvious. I am also not entirely sure if this has something to do with WP or purely PHP mechanics at work. <code> function test() { global $wp_query; var_dump($wp_query == $GLOBALS['wp_query']); } function test2() { global $wp_query; query_posts(array('posts_per_page' => 1)); var_dump($wp_query == $GLOBALS['wp_query']); } test(); test2(); </code> Result: boolean true boolean false Why does <code> test() </code> evaluates that to <code> true </code> , but <code> test2() </code> evaluates that to <code> false </code> ?
|
Update with a better example <code> header( 'Content-Type: text/plain;charset=utf-8' ); error_reporting( E_ALL | E_STRICT ); function failed_unset() { // Copy the variable to the local namespace. global $foo; // Change the value. $foo = 2; // Remove the variable. unset ( $foo ); } function successful_unset() { // Remove the global variable unset ( $GLOBALS['foo'] ); } $foo = 1; print "Original: $foo\n"; failed_unset(); print "After failed_unset(): $foo\n"; successful_unset(); print "After successful_unset(): $foo\n"; </code> Result <code> Original: 1 After failed_unset(): 2 Notice: Undefined variable: foo in /srv/www/htdocs/global-unset.php on line 21 Call Stack: 0.0004 318712 1. {main}() /srv/www/htdocs/global-unset.php:0 After successful_unset(): </code> <code> unset() </code> doesn’t know anything about the global scope in the first function; the variable was just copied to the local namespace. Old answer From wp-includes/query.php : <code> function &query_posts($query) { unset($GLOBALS['wp_query']); $GLOBALS['wp_query'] =& new WP_Query(); return $GLOBALS['wp_query']->query($query); } </code> Do you see it? BTW: Someone has made a stackexchange-url ("nice flowchart") about this very topic. ;) Update <code> query_posts() </code> changes <code> $GLOBALS </code> while all references to the variable <code> $wp_query </code> that you made available per <code> global </code> are not affected by unset . That’s one reason to prefer <code> $GLOBALS </code> (besides readability).
|
query_posts() in function makes global $wp_query out of sync?
|
wordpress
|
I got social bookmarks in jQuery, but how can I get post titles and permalinks in this snippet? If I put <code> <?php echo get_permalink(); ?> </code> in there, the whole site gets blank. <code> $('a[rel=shareit-twitter]').attr('href', 'http://twitter.com/home?status=' + title + '%20-%20' + title); </code> UPDATE: Here's the whole jQuery for the bookmarking: <code> <script type="text/javascript"> jQuery( function() { //grab all the anchor tag with rel set to shareit $('a[rel=shareit], #shareit-box').click(function(e) { e.preventDefault(); //get the height, top and calculate the left value for the sharebox var height = $(this).height(); var top = $(this).offset().top; //get the left and find the center value var left = $(this).offset().left + ($(this).width() /2) - ($('#shareit-box').width() / 2); //grab the href value and explode the bar symbol to grab the url and title //the content should be in this format url|title var value = $(this).attr('href').split('|'); //assign the value to variables and encode it to url friendly var field = value[0]; var url = encodeURIComponent(value[0]); var title = encodeURIComponent(value[1]); //assign the height for the header, so that the link is cover $('#shareit-header').height(height); //display the box $('#shareit-box').show(); //set the position, the box should appear under the link and centered $('#shareit-box').css({'top':top, 'left':left}); //assign the url to the textfield $('#shareit-field').val(field); //make the bookmark media open in new tab/window $('a.shareit-sm').attr('target','_blank'); //Setup the bookmark media url and title $('a[rel=shareit-mail]').attr('href', 'http://mailto:?subject=' + title); $('a[rel=shareit-facebook]').attr('href', 'http://www.facebook.com/share.php?u=' + url + '&title=' + title); $('a[rel=shareit-posterous]').attr('href', 'http://posterous.com/share?linkto=' + url + '&title=' + title); $('a[rel=shareit-twitter]').attr('href', 'http://twitter.com/home?status=' + title + '%20-%20' + title); }); //onmouse out hide the shareit box $('#shareit-box').mouseleave(function () { $('#shareit-field').val(''); $(this).hide(); }); //hightlight the textfield on click event $('#shareit-field').click(function () { $(this).select(); }); }); </script> </code>
|
You must output the propper HTML to make it working. Specifically, the href-attribute needs to contain the URL and the title separated with the | sign, like <code> <a href="http://example.com/post-url|post-title" rel="shareit" ... </code> . That will enable the script you've posted above use a concrete URL and title. As I don't know you PHP code from your theme I can not give any further hints on how to output the correct URL or title, but probably <code> <?php the_permalink(); ?>|<?php the_title(); ?> </code> might do it. Take care, encodings do apply.
|
jquery bookmark links
|
wordpress
|
For example, at /wp-admin/upload.php are displayed the following filters by: All (6) | Images (6) | Unattached (6) How can I remove the "Unattached (6)" filter by? Thanks in advance.
|
As it turns out, with the introduction of the <code> WP_List_Table </code> class, view filter are now hookable and specifically you can filter out that detached link like so.. <code> add_filter( 'views_upload', 'upload_views_filterable' ); function upload_views_filterable( $views ) { unset( $views['detached']); return $views; } </code> Bye bye detached link!... :)
|
How to remove the Unattached filter on Media Library List?
|
wordpress
|
I am creating a WordPress theme for a record label. One aspect is the video gallery. I created the gallery using a custom post type called 'videos'. The code below is what I placed in my functions.php file to set up the post type: <code> add_action( 'init', 'create_my_post_types' ); function create_my_post_types() { register_post_type( 'videos', array( 'labels' => array( 'name' => __( 'Videos' ), 'singular_name' => __( 'Video' ), 'add_new' => 'Add New Video', 'edit' => 'Edit Video' ), 'public' => true, 'exclude_from_search' => false, 'supports' => array( 'title', 'editor', 'thumbnail','page-attributes','excerpt' ), 'rewrite' => array( 'slug' => 'videos', 'with_front' => false ), )); } </code> I also created a custom taxonomy called 'artists' so I can assign the artist name to each video I upload. <code> add_action( 'init', 'create_videos_taxonomies' ); function create_videos_taxonomies() { register_taxonomy( 'artist', 'videos', array( 'hierarchical' => false, 'label' => 'Artist', 'query_var' => true, 'show_tagcloud' => true, 'show_ui' => true, 'rewrite'=>array('slug' => 'artists', 'with_front' => false) ) ); } </code> At this point, everything works fine on the backend and the video page returns all of the videos successfully. On another area of my website, I have pages for every single artist. On any one of these artist pages, i would like to be able to loop through all of the videos in the custom post type I created, and only return results in a given taxonomy. Below is my code to loop through a custom post type: <code> <?php $loop = new WP_Query( array( 'post_type' => 'videos', 'post_child' => 0, 'posts_per_page' => 5 ) ); ?> <?php while ( $loop->have_posts() ) : $loop->the_post(); ?> <?php the_post_thumbnail( 'video' ); ?> <?php the_content(); ?> <?php endwhile; ?> </code> This successfully loops through the videos, and returns the 5 most recent. I need this to loop through all the videos with a specific taxonomy slug or ID. For instance, I created a taxonomy called 'Smash Palace' and it has a slug of 'smash-palace' and an id of '17'. Any idea how I can loop though this custom post type and only return results in a given taxonomy?
|
Check the documentation here: http://codex.wordpress.org/Function_Reference/WP_Query#Taxonomy_Parameters You'll want to add this to your wp_query: <code> 'smash-palace' => 'smash-palace' </code> In other words, your new query would look something like: <code> $loop = new WP_Query( array( 'post_type' => 'videos', 'artists' => 'smash-palace', 'post_child' => 0, 'posts_per_page' => 5 ) ); </code> EDIT: I answered this question under the assumption that "Smash Palace" isn't actually a separate taxonomy , but a term within your existing "Artists" taxonomy. If "Smash Palace" is actually a separate taxonomy, then the following should work: <code> $args = array ( 'tax_query' => array ( array ( 'post_type' => 'videos', 'taxonomy' => 'smash-palace', 'field' => 'slug', 'terms' => 'slug-of-your-term' ) ) ); $query = new WP_Query( $args ); if( $query->have_posts() ) { while ( $query->have_posts() ) : $query->the_post(); // output your stuff endwhile; } </code> One thing I noticed: if you do not define "terms" in the <code> tax_query </code> array, you may get unexpected results (or none at all). You can query multiple terms at once like this: <code> $args = array ( 'tax_query' => array ( ... 'terms' => array ( 'slug-of-term-one', 'slug-of-term-two' ) ) ) </code> I hope that helps -- let me know if I understood your question correctly.
|
looping though custom post types and only return results in a given taxonomy
|
wordpress
|
I had recently moved my wp site from a domain to other, but when I type in the new domain's address it gets redirected to the old domain/some_page. Is this any common problem? Is there any known solution to this? I had checked my code and it has no redirects to this page. Can someone give me a hand on this?
|
This is because the URL settings inside WordPress are still pointing to the old WordPress site. In other words, you didn't read the Moving WordPress article in the documentation. If your WordPress admin pages are still working, you can go to Settings → General, and change the WordPress URL and the Site Address to the correct values. If your WordPress site is completely broken, then you can add the following values to <code> wp-config.php </code> , which will have the same effect: <code> define('WP_HOME', 'http://your_server/your_blog_url'); define('WP_SITEURL', 'http://your_server/your_wordpress_url'); </code> Note that in most cases, the above two values will the same same, apart from exceptional circumstances.
|
My wordpress site gets redirected automatically to the old site any known solution for this?
|
wordpress
|
how can I tell WordPress, that if a user registers, it shall execute my function?
|
You can use <code> user_register </code> action hook which fires after a user has registered and passes <code> $user_id </code> as a variable: <code> add_action('user_register','my_function'); function my_function($user_id){ //do your stuff } </code>
|
WordPress Hook for user register
|
wordpress
|
I've followed a tutorial on Nettuts on how to add a custom button to TinyMCE (http://net.tutsplus.com/tutorials/wordpress/wordpress-shortcodes-the-right-way/) It works great and all, but i want to add many buttons and i wonder if there's a smart way to do this without having to duplicate all the code over and over. Here's the code i use for adding a button: <code> add_shortcode("quote", "quote"); function quote( $atts, $content = null ) { return '<div class="right text">"'.$content.'"</div>'; } add_action('init', 'add_button'); function add_button() { if ( current_user_can('edit_posts') && current_user_can('edit_pages') ) { add_filter('mce_external_plugins', 'add_plugin'); add_filter('mce_buttons_3', 'register_button'); } } function register_button($buttons) { array_push($buttons, "quote"); return $buttons; } function add_plugin($plugin_array) { $plugin_array['quote'] = get_bloginfo('template_url').'/js/customcodes.js'; return $plugin_array; } </code> And then i create a customcodes.js file with this code in: <code> (function() { tinymce.create('tinymce.plugins.quote', { init : function(ed, url) { ed.addButton('quote', { title : 'Add a Quote', image : url+'/image.png', onclick : function() { ed.selection.setContent('[quote]' + ed.selection.getContent() + '[/quote]'); } }); }, createControl : function(n, cm) { return null; }, }); tinymce.PluginManager.add('quote', tinymce.plugins.quote); })(); </code> So again, how can i add multiple buttons without having to do all this code for each new button? Thanks :) Sebastian
|
First add your additional buttons inside the buttons callback.. <code> function register_button($buttons) { array_push($buttons, "quote","wpse-rules"); return $buttons; } </code> Then add additional buttons function inside the plugin javascript.. <code> init : function(ed, url) { ed.addButton('quote', { title : 'Add a Quote', image : url+'/image.png', onclick : function() { ed.selection.setContent('[quote]' + ed.selection.getContent() + '[/quote]'); } }); ed.addButton('wpse-rules', { title : 'WPSE Rules', image : url+'/image.png', onclick : function() { alert( 'WPSE Rules!' ); } }); }, </code> And so on, for any additional buttons you want..
|
How to add multiple buttons to TinyMCE?
|
wordpress
|
I just created a custom post type named Catalog. Where authors can create as many entries they need. But I need to restrict/deny access to all admin parts: Posts, Profile, Media or other admin parts except their Catalog entries. Do I need to compare against $_SERVER['REQUEST_URI'] or theres a better way? Thanks in advance.
|
This is more difficult than it needs to be it seems. To code it without using a plugin I would suggest using <code> global $menu </code> and <code> global $submenu </code> as an array and unset them based on user role or user name. It might get more difficult if you want to define user role permissions outside default values. http://codex.wordpress.org/Roles_and_Capabilities You can find the values in wp-admin/menu.php , you must look in here. Or browse them here http://core.trac.wordpress.org/browser/branches/3.1/wp-admin/menu.php For example if you want to unset a menu in a function it would be something along the lines of: <code> function remove_menu() { global $menu; //remove post top level menu for editor role if current_user_can('editor'){ unset($menu[5]); } } add_action('admin_head', 'remove_menu'); // ($menu[5]) is the "Posts" menu </code> You can see a much more detailed example here http://hungred.com/how-to/remove-wordpress-admin-menu-affecting-wordpress-core-system/
|
Disable all admin UI access to authors (except to custom post type add, edit and modify)
|
wordpress
|
Based on solved question from: stackexchange-url ("How to add a checkbox element to attachments editor with example") Theres an example of multiple Checkboxes, for example: Colors, patterns, etc... A grouped list but using checkboxes? Tips to save and remember checked options on edit? Thanks in advance.
|
Like @Bainternet said, it is the same thing. Taking the code from the question you linked to, you can do it like this: <code> function filter_attachment_fields_to_edit( $form_fields, $post ) { $foo = (bool)get_post_meta( $post->ID, 'foo', true ); $bar = (bool)get_post_meta( $post->ID, 'bar', true ); $form_fields['foo'] = array( 'label' => 'Is Foo', 'input' => 'html', 'html' => '<label for="attachments-' . $post->ID . '-foo"> '. '<input type="checkbox" id="attachments-' . $post->ID . '-foo" name="attachments[' . $post->ID . '][foo]" value="1"' . ( $foo ? ' checked="checked"' : '' ) . ' /> Yes</label> ', 'value' => $foo, 'helps' => 'Check for yes' ); $form_fields['bar'] = array( 'label' => 'Is Bar', 'input' => 'html', 'html' => '<label for="attachments-' . $post->ID . '-bar"> '. '<input type="checkbox" id="attachments-'.$post->ID . '-bar" name="attachments[' . $post->ID . '][bar]" value="1"'.( $bar ? ' checked="checked"' : '' ).' /> Yes</label> ', 'value' => $bar, 'helps' => 'Check for yes' ); return $form_fields; } </code>
|
How to add multiple checkbox elements to media attachments?
|
wordpress
|
I don't even know where to start with this one. I'm using a theme that requires me to override server php.ini settings in my own php.ini with <code> allow_url_include = on </code> That setting at very least seems to be a security risk, according to many (and my webhost) at most it requires some other users on some other hosts to add that line to their own php.ini files or some theme features won't work. (Some popular hosts like Bluehost have <code> allow_url_include = on </code> as default.) Anyone know where in the theme functions to look to a) find what requires <code> allow_url_include = on </code> and b) how to start working on it to change it? Any of these types of constructs the culprit? 1) <code> <?php include "scripts/scripts-google.php"; global $wpdb; .... </code> 2) <code> <?php define('ABSPATH', dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))).'/'); include_once(ABSPATH.'wp-config.php'); </code> 3) <code> <?php include "scripts/scripts-upload.php"; ?> </code> 4) <code> function pg_inner_custom_box_1() { $dir = dirname(dirname(__FILE__)); include($dir.'/admin/gallery/display_galleries.php'); } </code> 5) <code> <a href="http://www.domain.com/presets/ <?php echo str_replace("-", "_", $presets->preset_name); ?>.jpg" id="single_image"> <img src="http://www.domain.com/presets/ <?php echo str_replace("-", "_", $presets->preset_name); ?>_sm.jpg" style="width:225px;" /></a> </code> 6) <code> RSS Feed (please include http://) <input type="text" name="social_rss" size="50" value="<?php echo $social_rss; ?>" /> </code>
|
Okay, first off, that's an incredibly badly made theme. Your item number 2 there indicates to me that he making AJAX calls in entirely the wrong way. Secondly, look for anything in the theme that is using http but not in a link. allow_url_include basically lets you include some PHP from a remote site, which is indeed bad, but he might just be using it wrong. If the theme was freely available, I could look at it and give you more information. Is this theme available for download?
|
Theme requires allow_url_include = on in php.ini
|
wordpress
|
How would I add the capability in Simple Twitter Connect (in the stc-publish.php file) to not tweet pages, either newly published or edited? I don't need it to be an admin option, just a change for a few of my sites. It looks like this function would be a good place to add the "don't tweet pages" capabilty (while retaining the check to prevent edited posts from being tweeted) as it checks for edited posts. How can one differentiate between posts and pages? <code> // this new function prevents edits to existing posts from auto-posting add_action('transition_post_status','stc_publish_auto_check',10,3); function stc_publish_auto_check($new, $old, $post) { if ($new == 'publish' && $old != 'publish') { $post_types = get_post_types( array('public' => true), 'objects' ); foreach ( $post_types as $post_type ) { if ( $post->post_type == $post_type->name ) { stc_publish_automatic($post->ID, $post); break; } } } } </code> Edit 4/03/11 Answer and better edit below.
|
Even better answer that doesn't involve changing the plugin: <code> remove_action('transition_post_status','stc_publish_auto_check',10,3); add_action('transition_post_status','my_custom_publish_rules',10,3); function my_custom_publish_rules($new, $old, $post) { if ($post->post_type == 'page') return; else stc_publish_auto_check($new, $old, $post); } </code> Put it in a theme's functions.php. Side note: Whenever you're dealing with a function called by an action or filter hook, then you can easily wrap the call in a different function and add your own code to that function instead. remove_action and remove_filter should be two tools you use a lot in your WP arsenal.
|
Add function to Simple Twitter Connect to not Tweet pages
|
wordpress
|
The tinyMCE "kitchen sink" toggle button shows/hides a row of buttons. I have successfully added my row of shortcode buttons to the tinyMCE editor, but I was wondering if there was a way to make my row only display when the kitchen sink button is clicked. I don't want to add the buttons directly to the kitchen sink row because I have lots of buttons that need their own row. So, can I make the kitchen sink button show two rows instead of one? Or is there some sort of modifier when I add my row to indicate that it should be toggled when the kitchen sink button is clicked? Here is the code I'm using to add my third row of buttons: <code> // add shortcode buttons to the tinyMCE editor row 3 function add_button_3() { if ( current_user_can('edit_posts') && current_user_can('edit_pages') ) { add_filter('mce_external_plugins', 'add_plugin_3'); add_filter('mce_buttons_3', 'register_button_3'); } } //setup array of shortcode buttons to add function register_button_3($buttons) { array_push($buttons, "dropcap", "divider", "quote", "pullquoteleft", "pullquoteright", "boxdark", "boxlight", "togglesimple", "togglebox", "tabs", "signoff", "columns", "smallbuttons", "largebuttons", "lists"); return $buttons; } //setup array for tinyMCE editor interface function add_plugin_3($plugin_array) { $plugin_array['lists'] = get_bloginfo('template_url').'/js/customcodes.js'; $plugin_array['signoff'] = get_bloginfo('template_url').'/js/customcodes.js'; $plugin_array['dropcap'] = get_bloginfo('template_url').'/js/customcodes.js'; $plugin_array['divider'] = get_bloginfo('template_url').'/js/customcodes.js'; $plugin_array['quote'] = get_bloginfo('template_url').'/js/customcodes.js'; $plugin_array['pullquoteleft'] = get_bloginfo('template_url').'/js/customcodes.js'; $plugin_array['pullquoteright'] = get_bloginfo('template_url').'/js/customcodes.js'; $plugin_array['boxdark'] = get_bloginfo('template_url').'/js/customcodes.js'; $plugin_array['boxlight'] = get_bloginfo('template_url').'/js/customcodes.js'; $plugin_array['togglesimple'] = get_bloginfo('template_url').'/js/customcodes.js'; $plugin_array['togglebox'] = get_bloginfo('template_url').'/js/customcodes.js'; $plugin_array['tabs'] = get_bloginfo('template_url').'/js/customcodes.js'; $plugin_array['columns'] = get_bloginfo('template_url').'/js/customcodes.js'; $plugin_array['smallbuttons'] = get_bloginfo('template_url').'/js/customcodes.js'; $plugin_array['largebuttons'] = get_bloginfo('template_url').'/js/customcodes.js'; return $plugin_array; } add_action('init', 'add_button_3'); // add the add_button function to the page init </code> However, the row that adds is not toggled by the kitchen sink button.
|
Yes! Use the <code> mce_buttons_2 </code> filter to add buttons to the second row. Use the <code> mce_buttons_3 </code> filter to add buttons to the third row. Here's an example of what I use: <code> function mytheme_mce_buttons_row_3($buttons) { $buttons[] = 'fontselect'; $buttons[] = 'fontsizeselect'; $buttons[] = 'code'; $buttons[] = 'sup'; $buttons[] = 'sub'; $buttons[] = 'backcolor'; $buttons[] = 'separator'; $buttons[] = 'hr'; $buttons[] = 'wp_page'; return $buttons; } add_filter("mce_buttons_3", "mytheme_mce_buttons_row_3"); </code> Just drop this in functions.php. (I put it in my Theme setup function, that gets hooked into <code> after_setup_theme </code> .) EDIT: I don't know if it makes a difference or not, but you're using <code> array_push($buttons, $button) </code> , while I'm using <code> $buttons[] = $button </code> Here's your code: <code> //setup array of shortcode buttons to add function register_button_3($buttons) { array_push($buttons, "dropcap"); array_push($buttons, "divider"); array_push($buttons, "quote"); array_push($buttons, "pullquoteleft"); array_push($buttons, "pullquoteright"); array_push($buttons, "boxdark"); array_push($buttons, "boxlight"); array_push($buttons, "togglesimple"); array_push($buttons, "togglebox"); array_push($buttons, "tabs"); array_push($buttons, "signoff"); array_push($buttons, "columns"); array_push($buttons, "smallbuttons"); array_push($buttons, "largebuttons"); array_push($buttons, "lists"); return $buttons; } add_filter('mce_buttons_3', 'register_button_3'); </code> Which, using my method, would look like this: <code> //setup array of shortcode buttons to add function register_button_3($buttons) { $buttons[] = 'dropcap'; $buttons[] = 'divider'; $buttons[] = 'quote'; $buttons[] = 'pullquoteleft'; $buttons[] = 'pullquoteright'; $buttons[] = 'boxdark'; $buttons[] = 'boxlight'; $buttons[] = 'togglesimple'; $buttons[] = 'togglebox'; $buttons[] = 'tabs'; $buttons[] = 'signoff'; $buttons[] = 'columns'; $buttons[] = 'smallbuttons'; $buttons[] = 'largebuttons'; $buttons[] = 'lists'; return $buttons; } add_filter('mce_buttons_3', 'register_button_3'); </code> Give that a try?
|
Is there a way to add another row to the tinyMCE kitchen sink toggle?
|
wordpress
|
I have made a multiple category. Each item belong to one or more category. So when display one item, i like to retreive the category of this item, and display all post that have belong to that category. Example. Chair : cat = sit, leather, one person So when display the chair, i like below to display all item that have : sit leather and one person as category Is there a plugsin that do that ?, or in php it's simple to do ?
|
<code> # according to your example: $categories = array ( 'sit', 'leather', 'one person' ); # get all id's by the category names foreach ($categories as $category_name) { $category = get_term_by( 'name', $category_name , 'category' ); $ids[] = $category->term_id; } # get all posts for the categories query_posts( 'cat='.join(',',$ids) ); </code> Sorry, I cannot test it right now, this is just a guess till tomorrow.
|
Category "same post" retreive and display
|
wordpress
|
Is there a way to remove 'category' from the slug when viewing posts in a particular category in WordPress 3.1 without it breaking? My client is asking me to remove it, but it seems necessary - I get a Page Not Found error when using this plugin: http://fortes.com/projects/wordpress/top-level-cats/ He also doesn't want to just change it to another word...very frustrating... Thanks, osu
|
I didn't test it myself, but maybe this tip could solve your problem: If you would like yoursite.com/category/projects/projectname/ to appear as yoursite.com/projects/projectname/ Simply enter /. as the value for Category base in the permalink settings page.
|
WordPress 3.1 removing 'category' from the slug
|
wordpress
|
First plugin, basic question... I am trying to print the variable <code> $xavi </code> from a plugin into a theme like this: <code> add_action('init', '_load_options'); function _load_options() { global $xavi; } </code> So that I can use it in a theme file like this: <code> <?=$xavi;?> </code> It doesn't look like <code> init </code> is the right action hook for this but the only other one that makes sense is <code> wp_head </code> and doesn't work either Any ideas which hook should I use or how should I define variables (maybe through an existing WP function/method instead of creating one from scratch)? Thanks!
|
Your webhost has disabled <code> register_globals </code> in the php.ini , so you have to "register" your variables manually everytime you want to use it. For example: <code> <?php global $xavi; echo $xavi; ?> </code> Another approach is using the <code> $GLOBALS </code> array: <code> <?php echo $GLOBALS['xavi']; ?> </code> But in my opinion, you should avoid using globals. Instead use a simple registry-class, which you can add/get your values. EDIT This isn't a WordPress specific solution and could be a bit of an overkill for this simple question. The registry pattern is an official programming design-pattern. Same goes for the singleton-pattern which I've used here too. What we do here is to store our content in a registry-object. It's singleton, so only one instance is created. I know, the problem isn't solved really. Instead of using the $GLOBALS array, we are using a registry class which is indeed also "global" as we call the instance everytime we need it. You don't have control, where you call it. Also the testing of a singleton class could be problematic. If you want more control, just look at the factory-pattern with dependancy injection. <code> class Webeo_Registry { /** * Array to store items * * @var array */ private $_objects = array(); /** * Stores the registry object * * @var Webeo_Registry */ private static $_instance = null; /** * Get the instance * * @return void */ public static function getInstance() { if (is_null(self::$_instance)) { self::$_instance = new self(); } return self::$_instance; } /** * Constructor * * @access private * @return void */ private function __construct() {} /** * Set an item by given key and value * * @param string $key * @param void $value * @return void */ public function __set($key, $value) { // maybe you want to check if the value already exists $this->_objects[$key] = $value; } /** * Get an item by key * * @param string $key Identifier for the registry item * @return void */ public function __get($key) { if(isset($this->_objects[$key])) { $result = $this->_objects[$key]; } else { $result = null; } return $result; } /** * Check if an item with the given key exists * * @param string $key * @return void */ public function __isset($key) { return isset($this->_objects[$key]); } /** * Delete an item with the given key * * @param string $key * @return void */ public function __unset($key) { unset($this->_objects[$key]); } /** * Make clone private, so nobody can clone the instance * * @return void */ private function __clone() {} } </code> In your plugin/theme, you only have to return the instance and you're ready to use it: <code> $registry = Webeo_Registry::getInstance(); // Define some options (just add it after the "->". The magic method __set will do the rest) $registry->optionA = 'awdawd'; $registry->optionB = array(1,2,3); // Check the content print_r($registry); // Remove an item unset($registry->optionA); // Check if option exists if(isset($registry->optionA)) { echo 'option exist'; } else { echo 'option does not exist'; } </code>
|
Variable from a plugin into a theme
|
wordpress
|
i hope you are well today, My question is just breif i am trying to query from a custom post type by a certain taxonomy only; to keep it streamline lets use the below as an example; Custom Post Type: 'Products'; Taxonomy: 'Categories'; Categories within 'Categories'; (1) Category 1 (2) Category 2 (3) Category 3 So i would like query posts from the Custom Post Type 'Products' and within 'Category 1' How would this be done ? Here is my code for what querying the custom post type and attempting to query the taxonomy category. <code> <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $post_per_page = -1; // -1 shows all posts $do_not_show_stickies = 1; // 0 to show stickies $args=array( 'post_type' => 'products', 'taxonomy' => 'category-1', 'paged' => $paged, 'posts_per_page' => $post_per_page, 'order' => 'ASC', ); $temp = $wp_query; // assign orginal query to temp variable for later use $wp_query = null; $wp_query = new WP_Query($args); if( have_posts() ) : while ($wp_query->have_posts()) : $wp_query->the_post(); ?> </code>
|
There are 3 ways of doing that: a) <code> ... 'category_name' => 'category-1' ... </code> b) <code> ... 'taxonomy' => 'category', 'term' => 'category-1', ... </code> c) <code> ... 'tax_query' => array( array( 'taxonomy' => 'category', 'terms' => array( 'category-1' ) ) ) ... </code> More info: http://codex.wordpress.org/Function_Reference/WP_Query
|
Query Custom Post by Taxonomy Category
|
wordpress
|
Hi im looking at hardcoding a wp plugin into a theme, the plugin is Calendar . This is what i have done as of yet: 1) Moved files from wp-content/plugins into a folder within theme folder and made the changes so that paths are followed correctly. 2) Set to populate database via an SQL query rather than via plugin activation 3) Altered role caps so that contributers can add / delete bookings etc What i am now wanting to do is remove the functionality of it having to be edited within wp-admin dashboard (even though its no longer in plugins folder it still requires editing in wp-admin, due to how the plugin sets the menus etc) and rather have post_author edit it on a created page within the theme (edit_booking.php). Its not so simple as taking out chunks of code and adding them into edit_booking.php (only the html works), im looking for a way how to port the whole thing over and away from wp-admin, im guessing that in wp-admin there are functions called via the header/footer that need also to be ported over into my own theme functions.php does anyone have experience of doing similar and care to share a few enlightening tidbits of info on how to go about this. Regards Martin
|
My first recommendation: Don't do it! If the plug-in author releases an update, you can and will run into conflicts. Particularly if someone installs both the new plugin and your theme at the same time. A much safer route is to build plugin support into your theme. Make things degrade gracefully in case the plugin doesn't exists, but don't actually code the plugin into your theme. If you're still intent on hard-coding things ... Put the entire plugin in a subfolder for your theme. Then, from your theme, call <code> activate_plugin() </code> to turn the plugin on.
|
Hardcode a Plugin into theme
|
wordpress
|
I use my own svn repositories for all my development. I am looking for an easy way to keep the svn repository wordpress provides for my plugin synced up with my own internal repository. The desired end result being that when I commit a change to my own internal repository it gets duplicated automatically to my repository at plugins.svn.wordpress.org. ANd just to make things fun and interesting, I do not have any access to the server where my svn repositorys are held, I use a svn hosting service.
|
Maybe the svn switch -- relocate repository option can help you here: svn switch --relocate oldURL newURL . ( http://svnbook.red-bean.com/en/1.1/re27.html ) But... a lot more options here: stackexchange-url ("stackexchange-url
|
Sync my svn repositories
|
wordpress
|
You probably noticed the trend of making custom designed plugin/theme options UIs, especially in the commercial ones (on CodeCanyon for example - custom boxes, tabs, accordions etc). I personally believe that UI should be unified in the first place and that is really easy in WP to achieve using some core's default HTML structure + CSS classes => following the styling guide. However it is maybe sometimes not enough and that's why why there is that trend. Another reason could be "branding" or just some "coolness effect". What do you think about this? Do you prefer some custom designed UIs or the default one and why? P.S. The main reason I ask this is also because these days I started with plugin development and I trying to make this decision of which path to choose.
|
Custom UI is great where it improves the experience and makes the task easier. After all, a plugin extends WordPress and therefore a lot of the time is extending the user interface. This might mean a screen that is arranged completely differently to any other screen, but if it is logical and understandable then there's no cause for confusion. Where custom styling is being used to 'brand' a plugin, it's just annoying and naff. Custom UI should respect the colour choice of the admin backend. I much prefer plugins that could be mistaken for being part of the core, and that should pretty much be the goal. So, respect the core UI but don't be restricted by it.
|
What do you think about custom designed plugin/theme options UIs?
|
wordpress
|
hey guys, any idea how I could filter all inline javascripts from the content()? thank you
|
Not tested, but I imagine <code> add_filter('the_content', 'wp_kses_post'); </code> will scrub it good. Might need playing with priority.
|
remove inline scripts from the_content() produced by plugins?
|
wordpress
|
How would I go about adding a column to the Page Admin area that would show the last revision date of all pages? Alongside the Author and Published Date columns? I need to keep an eye on the page edits that other users do, and right now, the Page Admin area will only show the published date for a published page and the last modified date of a draft. So I need to show the revision date by any user of each published page. Possibly complicating things is I have post/page revisions disabled in wp-config.php to keep the database down to size, so an action can't hook into already existing page revision metadata. But the database contains a <code> post_modified_gmt </code> metadata column, so can that be grabbed by a direct database query? Not a good idea? And would I use this kind of action? http://codex.wordpress.org/Plugin_API/Action_Reference/manage_posts_custom_column
|
Would need some prettifying, but basic code is following: <code> add_filter('manage_pages_columns', 'add_revised_column'); add_action('manage_pages_custom_column', 'echo_revised_column', 10, 2); function add_revised_column($columns) { $columns['revised'] = 'Revised'; return $columns; } function echo_revised_column($column, $id) { if ('revised' == $column) echo get_post_field('post_modified', $id); } </code>
|
Add "Page Revised" column to Admin
|
wordpress
|
My future posts are going missed. They are not getting published on the time they should, and it says "Missed Schedule". I read somewhere that it could be a server issue, so how can I fix it?
|
Added the following to my functions.php: <code> define('WPMS_DELAY',5); define('WPMS_OPTION','wp_missed_schedule'); function wpms_replacements_deactivate(){delete_option(WPMS_OPTION);}register_deactivation_hook(__FILE__,'wpms_replacements_deactivate'); function wpms_init(){ remove_action('publish_future_post','check_and_publish_future_post'); $last=get_option(WPMS_OPTION,false); if(($last!==false)&&($last>(time()-(WPMS_DELAY*60)))) return;update_option(WPMS_OPTION,time()); global$wpdb;$scheduledIDs=$wpdb->get_col( "SELECT`ID`FROM`{$wpdb->posts}`". "WHERE("."((`post_date`>0)&&(`post_date`<=CURRENT_TIMESTAMP())) OR"."((`post_date_gmt`>0)&&(`post_date_gmt`<=UTC_TIMESTAMP()))".") AND`post_status`='future' LIMIT 0,10"); if(!count($scheduledIDs))return; foreach($scheduledIDs as$scheduledID){if(!$scheduledID)continue;wp_publish_post($scheduledID);}} add_action('init','wpms_init',0) </code>
|
Missed schedule
|
wordpress
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.