INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How can I implement a simple post editor? I want a simple post editor for WordPress, it should be something like tumblr editor or the stackoverflow editor. My questions: 1. Is there any plugin I can use? (I just can't find it) 2. If no plugin, how can I implement it? Is there any example? (I saw one site has such editor using WordPress, but they have reworked their site now)
You can use the Stackexchange Editor with the WP-Markdown Plugin, created by Steve Harris in this Question.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "post editor" }
custom walker to add iconfont to wp_nav_menu I want to add the font awesome iconfont to my menu list items, so I need to make a custom Walker. Because the font per menu item will be different I was hoping to use the css class in the WP backend to add the name of the icon and then output that css class within the output of the walker. Example how it should become: $item_output .= '<a'. $attributes .'><i class="icon-' . [output css class WP backend] . '"></i>'; Does anyone know how to filter the CSS class to be able to add it to the custom walker? Thanks and Merry Xmas!
ok, I figured it out myself. instead of using the CSS class (as I cannot figure out how to filter it), I decided to use the description instead. under the lines with `$attributes` I have added this line: $description = ! empty( $item->description ) ? esc_attr( $item->description ) : ''; And then I added that to the output as: $item_output .= '<a'. $attributes .'><i class="icon-' . $description . '"></i>'; I would still be interested to hear whether it can be done with class too?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, customization, walker" }
How to no follow the paginated comments I am trying to find a way to add `rel="nofollow"` to my comments pagination links. Can anyone provide me with a hook or way to do so?
There are two special filters for that: add_filter( 'previous_comments_link_attributes', 'wpse_77217_comment_nofollow' ); add_filter( 'next_comments_link_attributes', 'wpse_77217_comment_nofollow' ); function wpse_77217_comment_nofollow() { return ' rel="nofollow"'; }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "comments, pagination" }
Nonces can be reused multiple times? Bug / Security issue? I've read that nonces are meant to be for one time use only, and after an ajax request, you should issue a new nonce so with the next ajax request, a new nonce would be sent to the server. However, I just tested repeated ajax requests using the same nonce token, and for each request `wp_verify_nonce` returned true on the same token, meaning it could be reused dozens of times. Is this intentional, or a bug? Do I still need to issue new nonces with each ajax request, or can the same one continue to work for all future requests?
In WordPress, nonces are specific to the user, the action being performed, and the time. With regards to time, a nonce is valid for 24 hours, and changes every 12 hours. This is considered an acceptable trade-off, since using a real number-used-once would involve adding a tracking system and having storage of the used nonces. Nonces are also hashed, and so the NONCE_SALT constant will be part of the resulting nonce as well. Changing the NONCE_SALT will invalidate all nonces immediately. You should issue a new nonce every time. This is so that if the timing or methodology needs to be adjusted in the future, then your code will continue to handle it appropriately.
stackexchange-wordpress
{ "answer_score": 11, "question_score": 7, "tags": "plugin development, ajax, security, nonce" }
Is it possible to bold certain words in a post title? I guess I would like to be able to include HTML tags within the title so that when the title is listed certain words are bolded. Is this possible? When I try to put HTML into the title, the tag itself is output (escaped) in the final page list.
Yes, you can use HTML elements in post titles by default. If your output is escaped a plugin or theme might have touched that. Disable all plugins and switch to TwentyEleven. This will help you to identify the source. Note that markup is stripped in some places where it is not allowed: `title` attributes and elements, feed markup, nav menus. You should not break that. Also make sure your markup is valid and allowed for your user role. The `kses` filter will try to remove it otherwise.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 6, "tags": "posts, css" }
IP address character limit my client in his template is using `<?php comment_author_IP(); ?>` to display IP's of comment authors. Recently he came to me with idea of limiting whole number to several characters. Final result should be something simillar to: > 192.168... How can i achieve it? I've tried with jquery but without success. It looked like it was not responding to the jquery code.. thank you!
You can filter `'get_comment_author_IP'`: add_filter( 'get_comment_author_IP', 'wpse_77254_trim_comment_ip' ); function wpse_77254_trim_comment_ip( $ip ) { return implode( '.', array_slice(explode( '.', $ip ), 2) ) . '…'; } Note this will fail with IPv6 addresses.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 5, "tags": "wp query, jquery, ip" }
Custom form that store input in database I have never used WordPress before, but have a lot of programming experience. My question is, how to create customs forms in WordPress? I need to create a form where a user fills some input fields and on submit the data should be stored in the database. I don't need any notification on saving. I also need to query the data and get the output in an HTML table. Thanks
I am going to use this solution, but it seams to be very customize and can that be a problem with themes and upgrades? * Link to solution
stackexchange-wordpress
{ "answer_score": 3, "question_score": 7, "tags": "database, forms" }
Turn off ms-files.php after network setup I have a multisite that was set up on WordPress 3.4. That means that uploads for sub-sites are stored in `wp-content/blogs.dir/{blog_id}/files` and are served through ms-files.php. In WordPress 3.5, ms-files.php was disbanded completely for new installs and uploads are stored and accessed at `wp-content/uploads/sites/{blog_id}`. Is there anyway I can switch my install from the pre-3.5 way of serving/uploading files to the new way? I would like to continue serving uploads through `files/` for current blogs, if possible.
In theory: 1. Move images from blogs.dir/SITENUM/files/ to /uploads/SITENUM/ (or make an alias) 2. Edit all sites so they don't look in /files/ but in /uploads/SITENUM/ 3. .htaccess, remove the ms-files.php line 4. Search/replace each posts table for each site, changing /files/ to /uploads/SITENUM/ A walk-through can be found here (dumping ms-files), this is not a trivial hack! It involves command-line usage, sql, and using a mu-plugin. ## Resources * wp.org/support/removing-ms-filesphp-after-upgrading-existing-multisite-to-35 * wp.org/support/remove-ms-files-rewriting * Dumping ms-files
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "multisite, uploads" }
Adding class to next/prev image link in attachment.php Is it possible to add a class or ID to next/prev image links in `attachment.php`? I tried like this but it didn't work: <?php next_image_link( false, 'Next', array('class' => 'next')); ?>
There two hooks to filter these links: `previous_image_link` and `next_image_link`. So we can add these classes per filter: add_filter( 'previous_image_link', 'wpse_77296_img_link_class' ); add_filter( 'next_image_link', 'wpse_77296_img_link_class' ); /** * Add CSS class to image navigation links. * * @wp-hook previous_image_link * @wp-hook next_image_link * @param string $link Complete markup * @return string */ function wpse_77296_img_link_class( $link ) { $class = 'next_image_link' === current_filter() ? 'next' : 'prev'; return str_replace( '<a ', "<a class='$class'", $link ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "attachments" }
Wysiwyg editor for P2 theme I really would like a nice frontside wysiwyg-editor for the P2 theme. Preferable a light one with only the most basic controls. Tried front-end-editor but not to fond of it´s looks and UX. Plain and simple are key.
This question is quite old but the plugin which answers this question is quite new (in fact not finished yet). <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "theme development, wysiwyg, theme p2" }
Can I leave off plugin textdomain for terms used in core? I've got a plugin that puts post statuses into post type admin menus. I'm in the middle of internationalizing it, and I'm wondering how to handle this situation. The plugin uses some unique strings that will get a textdomain like this: __( 'Select the post statuses to <strong>exclude</strong> from post type admin menus', 'csmpmsi' ) But then there are also cases where I'm using a core-related word for their core-related meaning like this: `__( 'Pages' )`. In this situation, it seems to make perfect sense for me to exclude the textdomain and take advantage of terms that are already localized in core. However, the codex seems very explicit: > If you're trying to translate a plugin, the same advice as above applies, except that > > * you must use a domain, which is loaded in a hook of your plugin > > * every translation call must become __('text', 'domain-name') > > So is this WP-kosher?
Never rely on core strings for translation, they may change or get a `context` parameter any time. Once that happens your users get a partially translated interface, and your translators have no way to fix that. Also keep in mind the same string is not necessary translated everywhere with the same word. Even without a context parameter it might be useful to use a different translation for your plugin in some languages. But this wouldn’t be possible if you don’t include the string in your plugin. See this chat discussion we had some days ago about this topic.
stackexchange-wordpress
{ "answer_score": 14, "question_score": 10, "tags": "plugins, localization" }
WordPress settings API error when checkbox unchecked I am trying to creating some custom options for a template I am developing but I am getting an error when the checkbox (Line 130) is unchecked: > Warning: Illegal string offset 'show_admin_dev' in E:\composite-cms\WordPress-Settings-Sandbox-master\lib\admin\pages\dev-page.php on line 11 This is the line that seems to be throwing the error: if ( $options['show_admin_dev'] == 1 ) The entire code can be found on GitHub.
Your problem is that you haven't included a sanitization function as the third parameter to register_settings on line 111. When no sanitization provided WordPress deletes the value of the option and creates a new one based **only** on what is passed in `$_POST`. Since unchecked checkboxes are not sent by the browser at all you end up with `$options['show_admin_dev']` being not set. You should try to add sanitization which adds the value if it is not in the option register_setting( 'ccms_developer_options', 'ccms_developer_options', 'ccms_developer_sanit' ); function ccms_developer_sanit($newval) { if (!isset($newval['show_admin_dev'])) $newval['show_admin_dev'] = 0; return $newval; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "theme development, errors, theme options, admin menu" }
Display post title on individual image attachment page How to display parent post title on individual image attachment page heading of the post gallery? Currently, it shows image name as page heading on image attachment page. Any help appreciated. Thanks
Use … echo get_the_title( $post->post_parent ); … where `$post` is the currently viewed attachment.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "title" }
WPMU on MySQL limited to 1GB of space? My MySQL databases are limited to 1024MB per 1 database but WPMU websites need to exceed that... Is there any way to make WPMU go and use `database_2` when `database_1` is already close to 1024MB? I can have: * `database_1` 1024MB * `database_2` 1024MB * `database_3` 1024MB * `database_4` 1024MB * etc. I can't have: * `database_1` 8192MB or more
There is no code I know of to automatically partition databases like that based on their size, but if you want to use something to manually split your system across multiple databases, then HyperDB is one way to do that. <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, database" }
multi-language WordPress site I am making multi-language site powered by WordPress. WPML is not free and it makes too many extra sql queries to database so it is not good solution for my site. qTranslate saves all languages in one database row and it is very complicated to move to another multi-language plugin later. <?php _e( '<!--:en-->english text<!--:--><!--:de-->german text<!--:-->' ); ?> xLanguage hasn't been updated in over 2 years. Is there any other **plugin to manage multi-language site**? I have an idea to install WordPress as multisite **and each language will have its own site**. Is it good practice? !enter image description here
i set up my wordpress site as a wordpress multisite and then used "multisite language switcher" plugin... it is free and works great...
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "multi language" }
categories on attachment page I am using this function to display categories specified to a post having gallery on the image attachment page. <p>CATEGORY: <?php the_category(', '); ?></p> The problem is that this function doesn't return anything. I have also used this way to display categories but no success: <?php $categories = get_the_category(); $separator = ', '; $output = ''; if($categories){ ?> <span>CATERGORY:</span> <?php foreach($categories as $category) { $output .= '<a href="'.get_category_link($category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$separator; } echo trim($output, $separator); } ?> Can anyone tell where problem lies??? Thanks
If you have **WordPress 3.5** this will work. < First you need to enable this in your theme, Put this in your functions.php file in your theme root. add_action('init', 'wpse_77390_enable_media_categories' , 1); function wpse_77390_enable_media_categories() { register_taxonomy_for_object_type('category', 'attachment'); } In your image.php or attachments.php file add: $tax = get_the_term_list( $post->ID, 'category' ); echo $tax; Then go and add some categories to a attachment.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "categories, media library" }
Add Role inherits? On the WordPress codex Add Role page it says how to add a role, but I can not figure out how to do it, or that is inherits. Specially the comment `//Use false to explicitly deny`. What does that mean? Does that mean if i do not say false to all the capability they can still do is if they guess the rigth URL? Can somebody tell me the difference between true and false in wp role perspective, and how I should use it? I am trying to make a user which can only edit pages. Nothing else. < $result = add_role('basic_contributor', 'Basic Contributor', array( 'read' => true, // True allows that capability 'edit_posts' => true, 'delete_posts' => false, // Use false to explicitly deny )); if (null !== $result) { echo 'Yay! New role created!'; } else { echo 'Oh... the basic_contributor role already exists.'; }
You must set to true for them to take affect. If you do not specify true they all default to NULL which in turn basically makes them false. So to create a roll that allows pages only: add_role('page_editor', 'Page Editor', array( 'read' => true, 'edit_others_pages' => true, 'edit_pages' => true, 'edit_published_pages' => true, 'delete_pages' => true, 'delete_published_pages' => true, 'publish_pages' => true, ));
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "user roles" }
How to get comments with mixed status using get_comments? Is there a way to get comments with more than one `status` using `get_comments` function? Let's say I would like to get both `trash` and `hold` comments. It is possible to do the same with posts: get_posts(array('post_status' => 'draft,private,trash')); get_posts(array('post_status' => array('draft', 'private', 'trash'))); What I want to do is: get_comments(array('status' => 'hold,trash')); get_comments(array('status' => array('hold', 'trash')));
As of the Wordpress codex there is no such option. But you could just combine two or more comment arrays using plain PHP: array_merge( get_comments( array( 'status' => 'hold' ) ), get_comments( array( 'status' => 'trash' ) ) ); < <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "functions, comments" }
Hide "Add media", HTML editor from TinyMCE I have a custom post type which supports editor. (WordPress version 3.5) I want to customize the editor for it. 1. Make it readonly 2. Hide "Add Media" button 3. Hide HTML editor 4. Remove status bar showing word count I am using the following code: add_filter( 'tiny_mce_before_init', function( $args ) { $args['readonly'] = 1; $args['media_buttons'] = 0; $args['theme_advanced_disable'] = "code"; return $args; }); Only readonly is working. Is it not possible to do other customization using `tiny_mce_before_init`?
It should be `'media_buttons' => FALSE`. array ( 'textarea_rows' => 5, 'media_buttons' => FALSE, 'teeny' => TRUE, 'tinymce' => TRUE ) … creates this editor: !enter image description here
stackexchange-wordpress
{ "answer_score": 8, "question_score": 7, "tags": "custom post types, uploads, tinymce, html editor" }
How to get the ID of the currently logged in user? I want to get the ID of the currently logged in user. I've found the function: `get_current_user_id` which seems to be working, however I'm not sure what 'current' means in this context. Meaning if the user views the profile of another user, then will the current user change to become the other user? In short I'm looking for a reliable way to always get only the id of the logged in user.
`get_current_user_id()` effectively does what @Giri had described in the first snippet. The internal Wordpress function-call chain eventually calls `get_currentuserinfo()` which already checks if there is a WP_User object, meaning a user is logged in. Thus, from what I can see in the linked code, `get_current_user_id()` always returns the ID of the user that is logged in or zero `0`. In the current default theme `twentytwelve` they are using `get_the_author_meta()` to retrieve information about the user, for whom the current author page is displayed. So the difference in WP terminology seems to be "user" for th current, logged in user and "author" for some user, identified by an ID. See: twentytwelve/author.php.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugin development, buddypress, user access, user registration, authentication" }
Job of meta_key meta_value fields in database tables I'm researching the structure of WordPress database and there is something that really get me confuesd. Could someone please explain, what is the _exact_ job of `meta_key` and `meta_value` fields in `wp_commentmeta`, `wp_postmeta`, `wp_usermeta` tables? What is the job of these tables anyway? I did read the Database Description in the Codex, but still don't get it.
Think of them as array key/value pairs (kinda). These tables are used to store additional data about particular posts, comments, or users. The `meta_key` is the name by which the `meta_value` is retrieved, plus you have associations with particular posts, comments, or users by means of IDs. As far as **_structure_** goes, that is about it. These are "extra info" tables. You can even add to them via the backend. `*_postmeta` is where the custom fields are stored. WordPress stores, and plugins and themes can store, a wide variety or information there. Some of those tables have critical information, like role/capability data, but you may also have relatively trivial data like someone's Jabber handle (Is that even around anymore?), or a favorite color.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "post meta, user meta, meta value" }
Cannot see dropdown shortcut to site dashboard in WordPress network why? As per title and following screenshot !enter image description here
Your user are not inside the user-list of each blog in network active; maybe you are Super-Admin. Go to 'Sites (All Sites)' --> Edit a blog in Sites --> Tab 'Users' --> Add your user to the list of users and see the dropdown.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, admin bar" }
How to add the category ID to admin page I want to add the categories ID to admin page. I call it for my `functions.php`: `require_once('includes/categories_custom_id.php');` The part of code: function categoriesColumnsHeader($columns) { $columns['catID'] = __('ID'); return $columns; } add_filter( 'manage_categories_columns', 'categoriesColumnsHeader' ); function categoriesColumnsRow($argument, $columnName, $categoryID){ if($columnName == 'catID'){ return $categoryID; } } add_filter( 'manage_categories_custom_column', 'categoriesColumnsRow', 10, 3 ); But it doesn't work. Any idea, how to do that? Thanks in advance.
The hooks for taxonomies are: * `"manage_edit-${taxonomy}_columns"` for the header * `"manage_edit-${taxonomy}_sortable_columns"` to make columns sortable * `"manage_${taxonomy}_custom_column"` for the cell content To catch all taxonomies write: foreach ( get_taxonomies() as $taxonomy ) { add_action( "manage_edit-${taxonomy}_columns", 't5_add_col' ); add_filter( "manage_edit-${taxonomy}_sortable_columns", 't5_add_col' ); add_filter( "manage_${taxonomy}_custom_column", 't5_show_id', 10, 3 ); } add_action( 'admin_print_styles-edit-tags.php', 't5_tax_id_style' ); function t5_add_col( $columns ) { return $columns + array ( 'tax_id' => 'ID' ); } function t5_show_id( $v, $name, $id ) { return 'tax_id' === $name ? $id : $v; } function t5_tax_id_style() { print '<style>#tax_id{width:4em}</style>'; }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "categories, functions, id" }
Post via git repository I want to be able to post via a git repo. For example I have a repo named "blog" which contains these files: first_post.md second_post.md another_post.md I want all these files to appear in my blog like normal posts. I also want to be able to edit the files from the admin panel too (not only via git). Is there any way to do that?
Like the comments on this question stated, there is far too little detail in your post and it is far too localized of a question for this forum, but here is a general idea of what a project of this nature would require: You would need to utilize the GitHub API to dynamically pull new posts, as well as to enable modifying of the content and reposting back to GitHub. You would also need to develop a plugin that handles the integration of a GitHub repo with the WordPress posts using the WordPress API. In general, posts are stored in a database. You would need to override (or supplement) this behavior with support for pulling from a new source (GitHub). All that said, this is a massive job for what seems like a very small payoff. If you don't mind me asking, why would you want to do this?
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, git, github" }
Taxonomies for Wordpress Media Library > **Possible Duplicate:** > How it is possible to use taxonomies on attachments? I know this has been a long debated issue with WP, but I was hoping that since the 3.5 upgrade, there has been some progress in categorizing images in the Media Library. Really, what I am hoping to accomplish is creating a set of categories for the images in the Media Library, and then assigning the current images, or future images, to those categories. Then, later down the road I could call them in a page template based on their category. Any ideas WPA? Many thanks.
See the question / answer on this link. The answer have 2 different solutions, easy with default categories and taxonomies and also a solution with custom taxonomies only for media.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories, custom taxonomy, media library" }
cannot update wordpress from 3.4.2 to 3.5 I am trying to update wordpress from 3.4.2 to 3.5 . However, when I update, I get my old version 3.4.2 back. What could be causing this? When I click on update it shows all the steps but in the final step it gives back the 3.4.2 screen and the version remains un updated.
It's likely that the files aren't writable by WP for whatever reason. Do a manual upgrade instead. <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "updates, automatic updates" }
How can I display wp_link_pages before a shortcode, if it is used, or display after content? I have the following shortcode in my content [src]<a href="#">Some Link</a>, <a href="#">Some Other Link</a>[/src] My post structure looks like this: <?php echo $content; ?> <?php wp_link_pages();?> If that shortcode is being used in the content, I'd like for wp_link_pages to appear before it, if not, I would like it to display after the content. What's the best way to achieve this?
Do something like this. // your shortcode callback function your_sc_callback($atts,$content) { $content = wp_list_pages(array('echo'=>false)).$content; define('YOUR_SC_RAN',true); return $content; } Now, in your theme template after the content prints if (!defined('YOUR_SC_RAN')) { wp_list_pages(); } Or, you could do ... function append_list_pages($content) { return $content.wp_list_pages(array('echo'=>false)); } add_filter('the_content','append_list_pages',100); And your shortcode callback would be ... function your_sc_callback($atts,$content) { $content = wp_list_pages(array('echo'=>false)).$content; remove_filter( 'the_content','append_list_pages',100 ); return $content; } Both or these are untested, so no guarantees, but I think either should work.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "filters, shortcode, wp link pages" }
WordPress Pages into Sections edit.php PHP hack Im currently working on a Theme for a WordPress website. The theme affectively splits the website up into three sections. I need to be able to split up Pages in the backend into these sections. So in the menu it appears: - Pages - Section 1 - Section 2 - Section 3 And when you go into the relevant section the "Add New Page" button would set the pages parent to be the corresponding section. I realise this is very complicated,I currently have divided the menu but need to provide functions for each menu item. Is there anyway to do this with action hooks? Or will I have to edit the core files new-post.php and edit.php?
> I need this to be done with PHP so that the user cannot set the Parent. I asked this over on WP.SE and got a promising answer: Creating new page with pre-defined parent page I haven't got around to testing it yet, though, as the project is on hold. > And I need to know how to divide up the pages into the relevant sections. I'm not sure what you mean by that and how deep a division you need in your project. To display the three sections, you could use `wp_list_pages()` three times, and use the `child_of` parameter to pick the right section. Or you could have three menus in the backend, and call each of them using `wp_nav_menu()`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, plugins" }
How to allow visitors to filter posts by multiple taxonomies I am trying to allow users to filter a custom post type list by multiple taxonomies. For Example lets say my custom post type is **clothing** and it has two custom taxonomies **brand** and **type** associated with it. I would like a visitor to first see all clothing posts, then they could click on a brand link that brings them to a listing of all clothing in that brand(I can do this part). From that list of clothing in the chosen brand, I'd like them to be able to further narrow down the list to a type of clothing such as pants, so that now they are seeing a list of pants made by the brand they previously chose. I've looked around, and I found an older post showing how to do this by creating some rewrite rules: but, I'm really hoping there's an easier way than using rewrite rules out there now. Can anyone point me in the right direction here?
Alright well this might not be ideal, but it works and was much simpler than I thought! I ended up just adding a $_GET parameter to the 2nd taxonomy terms' linked url, so I could get the 2nd term from the other taxonomy on the next page through $_GET. On the next template I built a new WP_Query that uses the tax_query parameters to return posts from both taxonomy' terms, if the 2nd taxonomies term is set. Any thoughts on a better approach are still very much welcome. * * *
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "posts, custom taxonomy, filters, customization" }
Archive page showing wrong month My site's archive page is echoing wrong Month name. Though the URL is `2012/11/`, it's echoing the month `December 2012`. I found nothing wrong with the code: <?php if ( is_day() ) : printf( __( 'Daywise Posts: %s', 'theme-name' ), '<span id="font">' . "<b><i>". get_the_date() . "</b></i>" . '</span>' ); elseif ( is_month() ) : printf( __( 'Month-wise Posts: %s', 'theme-name' ), '<span id="font">' . "<b><i>". get_the_date( _x( 'F Y', 'monthly archives date format', 'theme-name' ) ) . "</b></i>". '</span>' ); elseif ( is_year() ) : printf( __( 'Year-wise Posts: %s', 'theme-name' ), '<span id="font">' . "<b><i>" . get_the_date( _x( 'Y', 'yearly archives date format', 'theme-name' ) ) . "</b></i>". '</span>' ); else : _e( 'Archives', 'theme-name' ); endif; ?> It's WordPress 3.4.2 here.
Try adding the following above the first if statement to see what actual day is being useddisplayed: echo get_the_date(); It might also help to add the following lines to help debug exactly what the query is doing: global $wp_query; var_dump($wp_query); The code is correct - so it has to be something else affecting the display. Does it do this for every month or just specific ones?
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "archives" }
Add code just after Post content I am in a bit of dilemma here so bare with me. I want to add something like this code just after the content in a post: <p>Please let me know what you think by <a href="#comment">leaving a comment</a>!</p> To do this, I edited `single.php` and added it after the content. However, the problem is that many of my posts are separated in several pages by using `<!--nextpage-->` and the above code is displayed on **every page**. I want that line to be displayed only at the final page if the post is separated. How is such thing possible?
There are some global variables available (or not) to detect the current page number: if ( empty ( $GLOBALS['multipage'] ) or $GLOBALS['numpages'] === $GLOBALS['page'] ) echo '<a id="lastPageLink" href="#comment">comment</a>'; The best way to understand what they do is a look at the internals of `wp_link_pages()`. * `(bool) $GLOBALS['multipage']` is `TRUE` if there is more than one page. * `(int) $GLOBALS['numpages']` is the amount of available pages. * `(int) $GLOBALS['page']` is the number of the current page. In JavaScript you can add an `onclick` handler like this now: document.getElementById("lastPageLink").onclick = function() { window.location.hash = 'comment'; document.getElementById('comment').focus(); return false; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "posts, html, single" }
Allow contributor role to upload images and not edit already published articles I have the following two requirements: 1. I want to allow users with the contributor role to upload media (images mostly) in their posts and preferably they shouldn't be able to delete existing ones before submitting it for review. 2. I want to make sure once an article is published that it can't be edited by the contributor (the writer of the plugin with user role contributor) or if it can be edited the newer version isn't updated before going through a submission process. I was recommended the Role Scoper plugin but I couldn't figure out how to do it. Any information about any other plugin or how to do this in Role Scoper would be great.
You can do all of this using the User Role Editor plugin. I normally tend to avoid answering questions by linking directly to a plugin but in this case, what you need comes in this package.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 7, "tags": "images, uploads, user roles" }
Add log in link to menu in Twenty Twelve I can't find a way to add the log in link to the new theme of WordPress, Twenty Twelve. I did find a lot of answers on the older theme, where they suggest to add some code in the `functions.php` file. However, this do not work for me. Does anyone have a solution for this? You can see my homepage here: <
Filter `wp_nav_menu_objects` and add the link as item, similar to this answer. add_filter( 'wp_nav_menu_objects', 't5_menu_log_link', 10, 2 ); /** * Add a link to the nav menu. * * @wp-hook wp_nav_menu_objects * @param array $sorted_menu_items Existing nav menu items * @param object $args Nav menu arguments. 'add_loginout' must be TRUE * @return array Nav menu items */ function t5_menu_log_link( $sorted_menu_items, $args ) { $is_in = is_user_logged_in(); $link = new stdClass; $link->title = __( $is_in ? 'Log Out' : 'Log In' ); $link->menu_item_parent = 0; $link->ID = ''; $link->db_id = ''; $link->url = $is_in ? wp_logout_url() : wp_login_url(); $sorted_menu_items[] = $link; return $sorted_menu_items; } Get it as plugin from GitHub.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, login" }
Custom columns for taxonomy list table I have the following code to add a new column to my taxonomy edit screen (`edit-tags.php?taxonomy=book_place&post_type=books`) function add_book_place_columns( $columns ) { $columns['foo'] = 'Foo'; return $columns; } add_filter( 'manage_edit-book_place_columns', 'add_book_place_columns' ); function add_book_place_column_content( $content ) { content = 'test'; return $content; } add_filter( 'manage_book_place_custom_column', 'add_book_place_column_content' ); It's working, but I need to access the current term id in the `add_book_place_column_content` function. How can I do that?
The `manage_{TAXONOMY}_custom_column` filter hook passes 3 arguments: * `$content` * `$column_name` * `$term_id` So try this: function add_book_place_column_content( $content, $column_name, $term_id ) { $term= get_term( $term_id, 'book_place' ); switch ( $column_name ) { case 'foo': // Do your stuff here with $term or $term_id $content = 'test'; break; default: break; } return $content; } add_filter( 'manage_book_place_custom_column', 'add_book_place_column_content', 10, 3 );
stackexchange-wordpress
{ "answer_score": 23, "question_score": 14, "tags": "taxonomy, columns, wp list table, screen columns" }
Remove the columns in media library How can i disable/remove the columns for Media Library? I want for **author** and **comments** column. Thanks in advance.
The hook for these columns is `manage_media_columns`. So just filter the columns here: add_filter( 'manage_media_columns', 'wpse_77687_remove_media_columns' ); function wpse_77687_remove_media_columns( $columns ) { unset( $columns['author'] ); unset( $columns['comments'] ); return $columns; }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "media library, columns" }
How do I use the WP image functions in a page template? Wordpress has tons of mature code for image editing on the admin side, but I would like to provide a form inside of a custom page template for my visitors to drag and drop, crop and save a thumbnail image as part of a new draft post. I can do the page template, form, and draft post part, but am getting pretty frustrated trying to integrate the plupload, jcrop and gd library parts. I can do bits and pieces using each of those libraries but can't get them to play nice and it's getting way too complicated for me. Then it hit me: WordPress can do all that magic stuff on the admin side already (having "bundled" those common libraries), so if I can leverage those wp core functions from the front-end, I will be done. Can anyone give me an example or two on how to use those wp core media functions from inside a user-facing page template? Please see my similar post on wp.org
The two key things I was missing was the realization that those javascript libs must be literally enqueued on the user-facing page that I intend to use them, and just experience on the mechanics of sending data between javascript and php by means of ajax and json.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 6, "tags": "functions, media, core" }
Is it possible to use object in add_action? So is it possible to do something like this with `add_action`? class class{} $my_class = new class; add_action('init', 'my_class');
You can do this: class testclass { function test() { echo 'howdy'; } } add_action('wp_head',array('testclass','test')); Or this: $t = new testclass(); add_action('wp_head',array($t,'test')); It doesn't work like... $t = new testclass(); add_action('wp_head','t'); // or this either, for good measure $t = new testclass(); add_action('wp_head',array('t')); .. but I am not sure what you are trying to accomplish by using that pattern. You've already instantiated the class so the constructor, if present, has already ran. Without a callback method, I don't know what you expect to happen.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 5, "tags": "filters, actions" }
Wordpress excerpt for specific posts in category Is there any way to create "more" link for excerpt only for posts in a specific category? For example only posts in "news" category should have a more link. If there's no option for that, maybe posts in specified WP Query? I am using this code for creating "more" link for excerpts but it works for _all_ posts: function excerpt_read_more_link( $output ) { global $post; return $output . '<a href="'. get_permalink( $post->ID ) . '">more</a>'; } add_filter( 'the_excerpt', 'excerpt_read_more_link' ); toscho thak You for reply. I will check Your solution, but I remeber that I used this code: if (in_category('news')) { function excerpt_read_more_link( $output ) { global $post; return $output . '<a href="'. get_permalink( $post->ID ) . '">more</a>'; add_filter( 'the_excerpt', 'excerpt_read_more_link' ); } and this didn't work :-/
Modify the callback and check the post category: function excerpt_read_more_link( $output ) { global $post; if ( in_category( 'news', $post ) ) return $output . '<a href="'. get_permalink( $post->ID ) . '">more</a>'; return $output; } And you should prefix the function name. In its current form it is not safe enough.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, excerpt, read more" }
How to add a class when there's no sidebar? I would like to add a class to a page template's body if the sidebar is not defined. How can I do that?
if you are using an actual page template (as selected in the dropdown panel in the admin area) then using is_page_template('file-name.php') in the body_class function will do it. then, the CSS would be body.class-name #content would apply to only that template area.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "sidebar" }
Installed WordPress with Softaculous. Should I upgradeManually or with Softaculous? I've setup my first blog with WordPress and I love the framework. I've created sites from scratch on a LAMP stack so I've even been able to tweak my theme and write a plugin or two. So, here's my question: I installed WordPress with Softaculous because it was easy and it worked the first time. Now, I've been upgrading WordPress and all of my themes and plugins manually from the admin panel on the blog. I thought this was a good way to go but I just logged into Softaculous to create a new blog and I noticed that it was telling me to upgrade the first blog that I created. Can I ignore the upgrade message in Softaculous and continue to upgrade the blog manually? Should I just use Softaculous to make it easy to upgrade multiple installs? Can I mix the two? Thanks for your hints, tips and tricks.
I had a similar situation with my WordPress install and Softaculous, what I found was that the version it was telling me to install (or upgrade to) was actually a minor version BEHIND the version of WP that was considered to be current at the time. In my situation I simply ignored it and had no issues.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "upgrade" }
Content management for static pages A corporate website has a few static pages, each with a specific layout, several independent blocks of text (located in different columns or zones of the page) and images. So far I handled this by designing a unique page template for each unique such page. But what if a client wants the ability to content manage these (a request which from his point of view sounds natural enough)? Is there an easy way to achieve that?
In this situation, I'll typically add meta boxes with new instances of the editor, but it's not for the faint of heart, that is to say, those not well-versed in php and javascript. If you want a simple solution for multiple editors on a page and don't mind relying on a plugin, you can achieve this very easily with Advanced Custom Fields.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "cms" }
Get image paths from RSS feeds I'm displaying the content from one wordpress blog page on my server onto a different wordpress blog on the same server. Apparently the only way is through RSS feed. The images don't show up. I var_dumped the RSS object and there are no image paths. How do I get the image paths, or the filename of the image? Or how do I force the source blog to include the image information in the feed.
Images are in the feed, if the feed is a fullfeed, not a excerpt. Check the xml snytax in atom format for `<content:encoded>` or in RSS2 for `<description>`. In this tags you can find the images of the content.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, multisite, rss, blog" }
Problem with wp_create_category I have simple code: add_action('init', 'categoryTransfer'); function categoryTransfer(){ //some code for($i=0; $i < count($categories); $i++) wp_create_category($categories[$i]->name); } But when it executes i get: Fatal error: Call to undefined function wp_create_category() in /Users/noname/Sites/wp-content/plugins/my_plugin/my_plugin.php on line 95 Where is a problem?
This function is declared in `wp-admin/includes/taxonomy.php`. This file will be loaded in `wp-admin/includes/admin.php`. And that now is called in `wp-admin/admin.php`. So the solution is: Use the hook `'admin_init'` or require all necessary files manually. But don’t do that on every request.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "categories" }
Can you ungroup Custom Fields? I have been using a lot of Custom Fields to make Wordpress like a CMS, beyond simple posts and post meta. The admin area for adding new posts has little "widgetized" movable areas like the "categories", "publish," and "tags" boxes for instance. With Custom Fields, all are grouped under one "widget" with the same name. Is there a way to break out the Custom Fields into their own "widget" boxes to rearrange the placement of the admin area?
You can create and position your own meta boxes via `add_meta_box`. You can store the data as meta data behind the scenes but it will allow you to customize the UI in the admin screens.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "custom field, wp admin" }
Change Label for field used in Woo Commerce I'm using WooCommerce, and using a BACS Payment method which is actually Bank Trasnfer. The fields account details are fine, but for Indian context.. i need to change following two fields labels to something else. For example: Change IBAN label to MICR Code, and BIC to IFSC. And also need to disable Sort Code. However, please note that I don't to make chanegs into plugin's code itself. So looking for some function that can help change the label from my theme function file. Any help is appreciated.
It gets its label using a localisation call, `__('IBAN', 'woocommerce')`, so you could always just intercept that and change the text: /** * filter translations, to replace some WooCommerce text with our own * @param string $translation the translated text * @param string $text the text before translation * @param string $domain the gettext domain for translation * @return string */ function wpse_77783_woo_bacs_ibn($translation, $text, $domain) { if ($domain == 'woocommerce') { switch ($text) { case 'IBAN': $translation = 'MICR'; break; case 'BIC': $translation = 'IFSC'; break; } } return $translation; } add_filter('gettext', 'wpse_77783_woo_bacs_ibn', 10, 3);
stackexchange-wordpress
{ "answer_score": 5, "question_score": 6, "tags": "plugins" }
Custom PHP-coding in MU installs I have a WPMU install with a couple of sites on it. I'd like to add some subdirectories that are not wordpress blog pages but do contain working PHP code. They do not use any of wordpress's libraries and are not plugins. The catch is that I'd like these subdirectories to only show up on a particular site. For instance, the hierarchy is: /wordpress/customapp but should work while should give a 404 error. Is there anyway to do this? I'm running Wordpress through Windows Server IIS7 if it is any help. Thanks
I added the following section to the top of my web.config rewrite rules section: <rule name="Movies Redirect" stopProcessing="false"> <match url="\/?movies\.*" /> <conditions> <add input="{HTTP_HOST}" pattern="^.*dawson\.osmblags\.com.*$" negate="true" /> </conditions> <action type="Rewrite" url="{C:0}" /> </rule> This is working. Anytime someone attempts to go to something.osmblags.com/movies it redirects them back to something.osmblags.com rather than allowing them to view the custom code section. It limits the available permalinks but works fine for my purposes.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, multisite, customization" }
Changing Link Attributes for Wp_Link_Pages I'm wondering if there is any way to change the actual link itself for wp_link_pages. So right now, I have a simple code to display the pagination for a post, it looks like this: `<?php wp_link_pages( array( 'before' => '<div class="link-pages">' . __('Pages:', 'muimedia'), 'after' => '</div>',) ); ?>` It displays the Post pagination like so: Pages: 1 2 3 Page one links two page one, page two links to page 2 etc. Now, I would like to add an attribute called `fromwhere=news"` to the pagination permalinks. So page 1, 2, and 3 pagination links would look like so.. `mysite.com/somepost/post?fromwhere=news"` instead of just `mysite.com/somepost/post` I really hope this is possible, and if anyone could help me out, it would really mean a lot to me! And happy new years!!! :)
There is no filter for the URLs, and no filter for the complete output of `wp_link_pages()`. But you can get the output as string if you pass `'echo' => FALSE` as argument. There are four options: 1. Write a modified copy of the function with the URLs you need. You will miss all further improvements which may happen in core code. 2. Catch the output in a string and run a regex on that. Example: print preg_replace( '~(href=")([^"]+)~', '\1\2?from=' . $post->post_name, wp_link_pages( array ( 'echo' => FALSE ) ) ); 3. Use JavaScript to add the parameter. 4. Do nothing. Do not offer the same content – separate sub pages – with different URLs (a search result could link to a sub page too), and make external search engines like Google happy.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "php, pagination" }
Custom avatars in wordpress comments? I'm looking for a way to let people connect with facebook when posting comments, and to use their facebook avatars as the avatar for the comments. How can this be done? Do I need to create a seperate user account for those people, or is their a way to simply store an avatar url for each comment that's posted?
Three simple steps to generate a Facebook Avatar: 1. Create an extra field in your comment form for the user's facebook profile (see e.g. WP Engineer for a code example and how to) 2. If the user filled out this field, get the facebook avatar (see this question) 3. Replace the WP avatar with your facebook avatar if a fb profile url is set All together in this Gist ( **PHP5.3 required!** ). Tested with WP3.5 and FireFox/Chrome **Hint:** It is strongly advised to read the code comments. There are several informations how to configure the plugin e.g. in the functions.php.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development, comments, facebook, avatar" }
Custom pagination code is not working I am using the below code for pagination. However, it is not working. It's showing all of the pages numbers nicely, but when I click on a page number the first page is always displayed. global $wp_query; $total_pages = $wp_query->max_num_pages; if ( $total_pages > 1 ) { $current_page = max( 1, get_query_var( 'paged' ) ); echo paginate_links( array( 'base' => get_pagenum_link( 1 ) . '%_%', 'format' => '/page/%#%', 'current' => $current_page, 'total' => $total_pages, ) ); } My permalink settings are set to: > localhost/my-blog/sample-post/ And query post: > $args = array( 'post_type' => 'post', 'posts_per_page' => 2); If i change the format to > '/page=%#%' its providing me 404 error. anybody please give me idea what to do next for working this pagination.
check below code for pagination. global $paged; $temp = $wp_query; $wp_query = null; $wp_query = new WP_Query( array('post_type' => 'post','posts_per_page' => 2, 'paged' => $paged ) ); while (have_posts()) : the_post(); // Your post content. endwhile; echo paginate_links( $args ); global $wp_query; $big = 999999999; // need an unlikely integer echo paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => $wp_query->max_num_pages, 'prev_text' => __('Previous'), 'next_text' => __('Next') ) ); /* Code Ends Check this code and let me know.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "pagination" }
Admin can enter JavaScript - potential security risk? WP 3.5/TwentyTwelve/Clean install. I try this when login as admin and editor. I try add reply for first post "Hello World": <script>alert('XSS')</script><script><</script> and get popup window !enter image description here. Is it porential security risk or can no care? Thanks for advance..
The answer is in your question. > I try this when login as admin and editor. The roles have the `unfiltered_html` capability that allows them to put whatever HTML they choose, including `<script>` tags, where ever they choose. Is is a security risk? Only if you give folks you don't trust admin and/or editor roles. Or someone gains access to your an admin/editor account. Or there's another security hole somewhere in the core that allows privilege escalation from a lower to higher user level (unlikely). By itself, it's not a security risk. Admin and editors need to be able to do things to actually manage the site.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 0, "tags": "comments, javascript, security" }
Display user registration date I want to show user registration date like > Member since: 15,dec 2012. I have a code <?php echo date("M Y", strtotime(get_userdata(get_current_user_id( ))->user_registered)); ?> but it show same date in all users profiles. Can some one please tell me how I fix that.
`get_current_user_id()` give you the user id of the **logged in** user. And that is: you. You have to get all users: <?php $users = get_users(); foreach( $users as $user ) { $udata = get_userdata( $user->ID ); $registered = $udata->user_registered; printf( '%s member since %s<br>', $udata->data->display_name, date( "M Y", strtotime( $registered ) ) ); }
stackexchange-wordpress
{ "answer_score": 16, "question_score": 11, "tags": "users, date, user registration" }
Get the latest comment from a custom post type where depth = 1? Happy new year everyone. I've been struggling with this one for a while. I need to get the latest comment from a custom post type, but ignore any child comments i.e. only look at comments with a depth of 1. I can get the latest comment from a custom post type using: $args = array( 'post_type' => 'custom-post-type', 'number' => '1', 'orderby' => 'date', 'order' => 'DESC' ); $comments = get_comments($args); foreach($comments as $comment) : echo($comment->comment_author . '<br />' . $comment->comment_content); endforeach; However, it doesn't take into account the depth requirement. Any ideas how I can achieve this?
Set the "parent" parameter as 0. $args = array( 'parent' => 0, 'post_type' => 'custom-post-type', 'number' => '1', 'orderby' => 'date', 'order' => 'DESC' ); $comments = get_comments($args); foreach($comments as $comment) : echo($comment->comment_author . '<br />' . $comment->comment_content); endforeach;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, comments" }
Disable WooCommerce action I'm customizing a WooCommerce theme and am going to be moving the title. There is an action in `content-single-product.php` called: do_action( 'woocommerce_single_product_summary' ); in the `woocommerce_hooks.php` file the title action is: add_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 ); I can easily comment this out and place the title function where I need to. I'd prefer to disable the title using a function in my themes `functions.php` file so I don't have to worry about modifying core files. What would the function be to disable this title action?
That would be: remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 ); You can read about it here: `remove_action` Codex
stackexchange-wordpress
{ "answer_score": 7, "question_score": 5, "tags": "actions, plugins, deactivation" }
Allow spiders to crawl my site (selectable option in wp) I was creating a site for testing and i selected an option when setting up wp that essentially disallows my site from being indexed/crawled. I would now like it to be crawled like normal, but i cant find the option within wordpress. I am running wp 3.5WP Thanks in advanced.
To allow crawling of your WP site you need to go to "admin panel >> Settings >> Reading" right before the "Save Changes" button is a checkbox with the label **Search Engine Visibility** make sure this is unchecked.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "options, seo" }
how can I create a WP offline environment before releasing the websites? GIT? SVN? WAMP? XAMP? MERCURIAL? BITNAMI? There are so many options that I am getting a bit confused. I just want to work without publishing and a need of an internet connection, and when all is ready, just release it.
You can use the XAMP server, I am also using the same for the last 5 years. And also you can consider to use Microsoft Web Matrix as the editor because it provides wordpress syntax highlighting, suggestions etc.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "git, svn, github, offline" }
Invalidate username if it contains @ symbol I would like to let the user login either using username or email. The only way to find the email is by detecting `@ symbol` using `strpos`. However WordPress allow `@ symbol` in username too. Can someone help me to invalidate username if it contains @ symbol in it..
In a multi-site installation it is `'wpmu_validate_user_signup'`: add_filter( 'wpmu_validate_user_signup', 'wpse_77904_mu_no_at_in_username' ); function wpse_77904_mu_no_at_in_username( $user ) { if ( FALSE !== strpos( $user['user_name'], '@' ) ) $user['errors']->add('user_name', __( 'That username is not allowed.' ) ); return $user; } On single-site it is `'validate_username'`: add_filter( 'validate_username', 'wpse_77904_no_at_in_username', 10, 2 ); function wpse_77904_no_at_in_username( $valid, $username ) { if ( FALSE !== strpos( $username, '@' ) ) return FALSE; return $valid; } Caveat: both not tested. :)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "login, email, sanitization, username" }
Organize template parts and page templates in folders in regards of template hierarchy Hello and happy new year Suppose one has a large theme composed of several post types, page templates and a bunch of custom loops and template parts which is best keeping in separate php files. What's the best practice to organise these files? For example, suppose I have 10 page templates. How about putting them in a folder named "pages"? And another folder for the archives? However, how to let Wordpress know where to look for the templates? Thanks
Page templates are special case and since WP 3.4 can be put in subfolder natively. Other than that WP mostly expects flat file structure for templates. While template hierarchy is easily adjusted (see dynamic filter in `get_query_template()`, pretty much only thing needed)... From personal experience - overly extensive and nested directory structure for templates makes developer workflow overly unpleasant very fast. If you have extreme quantity of templates "how to reduce amount?" is better question than "how to stuff them into folders?".
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "templates, page template, template tags, get template part, template hierarchy" }
Remove 'rel' attributes from the_category() output I am trying to get the categories associated with a post in it's meta section by using the following code: <div>FILED AS: <span class="gf-post-meta-result"><?php the_category(' &bull; ') ?></span></div> WordPress is generating the markup as: <div>FILED AS: <span class="gf-post-meta-result"> <a href=" title="View all posts in Uncategorized" rel="category tag">Uncategorized</a> </span></div> This part `rel="category tag"` is making my code invalid. W3C validator throws an error saying: > Bad value category tag for attribute rel on element a: The string category is not a registered keyword or absolute URL. Whitespace in path component. Use %20 in place of spaces. > > …w all posts in Uncategorized" rel="category tag">Uncategorized Any idea how to rectify this?
Filter `the_category`, and remove those attributes: add_filter( 'the_category', 't5_remove_cat_rel' ); function t5_remove_cat_rel( $list ) { return str_replace( array ( 'rel="category tag"', 'rel="category"' ), '', $list ); }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "categories, validation, customization, html" }
Retrieve the template directory URI via global or get_template_directory_uri() every time? One Wordpress function I happen to use frequently is `get_template_directory_uri()`. While I tried to minimize or avoid its use where I can, I still happen to have more than one call to this function in certain pages across my theme. Most of the time in a series of href or inside other functions (for which I normally put the URI resulting from `get_template_directory_uri()` in a `$variable` \- however I still find that I might have to store again that variable in a different php file). I wonder, would it be best if I store the returning value (my theme URI) in a global and use echo the global when I need it in different parts of my theme php files? I'm still learning my way to best practices and uses of variables and globals. Thank you
I would stay stick to the function. PHP caches functions for speed and efficiency. In some situations, using a function is _faster_ then using a variable. There are other benefits too - imagine if you changed the name of your variable - you would have to go and update every piece of code where it's used.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "theme development, templates, directory, variables, globals" }
How to include the 'current-menu-ancestor' class on a custom post type menu in Wordpress? I need the Wordpress menu to include the 'current-menu-ancestor' class to reflect that site is currently in the recipe section. Supposing I have a recipe custom post type. I have the following code in my functions.php but it's not working: function add_active_item_classes($classes = array(), $menu_item = false){ if ( get_post_type() == 'recipe' && $menu_item->title == 'Recipes') { $classes[] = 'current-menu-ancestor'; return $menuclasses; } } Also I don't know what filter hooks I will use to have this effect? Thanks for your suggestion and assistance.
This is the final working code: <?php function additional_active_item_classes($classes = array(), $menu_item = false){ global $wp_query; if(in_array('current-menu-item', $menu_item->classes)){ $classes[] = 'current-menu-item'; } if ( $menu_item->post_name == 'product' && is_post_type_archive('product') ) { $classes[] = 'current-menu-item'; } if ( $menu_item->post_name == 'product' && is_singular('product') ) { $classes[] = 'current-menu-item'; } return $classes; } add_filter( 'nav_menu_css_class', 'additional_active_item_classes', 10, 2 ); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 4, "tags": "menus" }
wordpress admin is broken I have just installed a fresh version of the latest wordpress locally but the backend admin area looks like this < Not sure what is causing this, I have tried redownloading and reinstalling witha new database but still doesnt work. uggh! DEBUG INFO I get the following error when I go to the updates page, but I have no errors or warnings on the homepage. Notice: ob_end_flush(): failed to send buffer of zlib output compression (0) in /Volumes/data/Documents/websites/mrskitson2012/wp-includes/functions.php on line 2690
Try clearing your browsers cache and reloading the page. That'll fix it. There is an explaination here (see problem number 2)
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "wp admin" }
Extensible code I would like to write this piece of code in an extendible way. $my_item = array( 'post_title' => $item->get_title(), 'post_content' => '', 'post_status' => 'publish', 'post_excerpt' => $item->get_description(), 'post_type' => 'post' ); If I use this in a plugin I would like to be able to create another plugin that can change that array and give different values or parameters. How can I do that?
Provide a filter: $my_item = apply_filters( 'plugin_name_item_args', array( 'post_title' => $item->get_title(), 'post_content' => '', 'post_status' => 'publish', 'post_excerpt' => $item->get_description(), 'post_type' => 'post' ), $item # pass the $item object to the filter ); A plugin can change these values now with: add_filter( 'plugin_name_item_args', 'another_plugin_filter', 10, 2 ); function another_plugin_filter( $args, $item ) { $args['post_type'] = 'page'; return $args }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "plugins" }
WordPress 3.5: Setting custom "full URL path to files" in the Media Library? As the recent changes in WordPress 3.5 removed the "full URL path to files" option from media library I am wondering how to set this option to a custom path now? I need to set my "full URL path to files" for my media files to a custom subdomain. Can you guys help me out with finding a solution for this problem? Regards, faxxim
The option name is `upload_url_path`, and you can still filter it: add_filter( 'pre_option_upload_url_path', 'wpse_77960_upload_url' ); function wpse_77960_upload_url() { return ' }
stackexchange-wordpress
{ "answer_score": 18, "question_score": 15, "tags": "uploads, media, media library" }
Display all authors in a theme template I was having an issue the other day and successfully got a very good answer which helped me alot achive what I wanted. this is the post which I created and have all the correspondence: wordpress.stackexchange.com/questions/63060/display-all-authors-and-their-only-one-latest-post The answer was kindly contributed courtesy of @Sagive SEO This script currently displays all authors in an order of most posts written. I would like to change it to simply display all authors randomly regardless of how many posts they wrote. Hope to get an answer, thanks a lot Gil
What you need here is to shuffle all the array elements & then display them. But since php's `shuffle()` function doesn't preserve array key associations, here's a version that does. function shuffle_assoc(&$array) { $keys = array_keys($array); shuffle($keys); foreach($keys as $key) { $new[(string)$key] = $array[$key]; } $array = $new; return true; } Add this function somewhere in your functions.php & replace `arsort($authorsArray);` with `shuffle_assoc($authorsArray);` in the code suggested in the previous question
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "author, list authors, author template" }
TinyMCE buttons broken For some reason my TinyMCE buttons are completely misaligned and have the wrong `background-position` (See image below): !enter image description here I have attempted to download a fresh install of Wordpress 3.5 and replaced my files with the following from it: /wp-includes/css/editor.min.css /wp-includes/images/wpicons.png However nothing changed. I haven't edited the admin stylesheet either.
**Solved:** It appears chrome had a corrupt cache as I attempted to visit the backend on Firefox and noticed that the issue wasn't there. I had to delete all Chrome browsing data (cache alone wouldn't do it).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "admin, tinymce, editor, dashboard" }
How to use add_settings_error in register_setting callback public function database_name_check($input){ //debug add_settings_error('notice', 'lol', 'lol'); if($this->wpdb->get_var($this->wpdb->prepare('SHOW DATABASES LIKE %s', $input)) == $input) return $input; else{ add_settings_error('notice', 'lol', 'lol'); return FALSE; } } I can not understand why the error does not exceed, any suggestions?
Take a look at the `add_settings_error` prototype. add_settings_error( $setting, $code, $message, $type ); The first argument is your settings name/key -- or if your setting is on another page (eg `general`) it should be the page key. The second is whatever you'd like to add to the ID attribute, then error/updated message, and finally type. It doesn't work because you're using it incorrectly. So you probably want... <?php add_settings_error( 'your_setting_key', // whatever you registered in `register_setting 'a_code_here', // doesn't really mater __('This is the message itself', 'wpse'), 'error', // error or notice works to make things pretty ); You also need to tell WordPress to display your settings errors. If it's on a custom page, you'll need to include `settings_errors` in the callback. settings_errors('your_setting_key');
stackexchange-wordpress
{ "answer_score": 11, "question_score": 1, "tags": "errors" }
What are the advantages and disadvantages of Option Tree over the Customization API? I'm relatively new to WordPress theme development, and I had to create a theme with options available. I did a Google search to see what are the possibilities, and I read articles about such, and read about frameworks, and I came across Option Tree, which was recommended as a framework to develop with. What my question is, when I'm developing themes to sell, what are the advantages and disadvantages of Option Tree over the Customization API built into WordPress?
disadvantage using option tree: 1. Your theme depend on other work as a core 2. You need to always keep an eye for the plugin update ( which is really not good if you're going to use it in premium theme ) 3. If you're going to integrate it in your theme, then when there is update from the plugin you will need to do lot of things to update it in your theme. advantage : 1. Save you the time to create your own theme options If you have lots of time I suggest you to create your own theme options which will be better if you're gonna use it in a premium theme to sell, you'll have more control over the theme options. And if you're not going to write your own script, I suggest you to use Options Framework Theme which is specially build to include in theme rather than using plugin. The author is keep updating the script itself so its safe to use it, I also use it in my premium theme.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 8, "tags": "theme development, theme options, plugin option tree" }
Wordpress 3.5 - Add custom image size Since the new version of Wordpress (3.5), it seems to be an incompatibility between the image manager and the custom image sizes. Previously I used in my functions.php : add_action( 'after_setup_theme', 'addemo_setup' ); function addemo_setup() { add_theme_support( 'post-thumbnails' ); add_image_size( 'featured-image', 375, 500, true ); } // Insert Custom Sized Image Into Post Using Media Gallery add_filter( 'image_size_names_choose', 'custom_image_sizes_choose' ); function custom_image_sizes_choose( $sizes ) { $custom_sizes = array( 'featured-image' => 'Featured Image' ); return array_merge( $sizes, $custom_sizes ); } When I add a thumbnail, I don't have any choice. Does anyone has encountered this problem ?
Instead of using the functions.php to add my custom image size, I installed the plugin Simple Image Size. This plugin does perfectly the job.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "thumbnails, images" }
need correction with a snippet in functions.php I use gravity forms and wp-favorites plugin (helps users select their favorite posts). I am trying to auto-populate gravity form with the following snippet. It works pretty well but it shows only the first item in the list. How can I get all items in the array? add_filter("gform_field_value_circle", "populate_square"); function populate_square ($value) { $favs = wpfp_get_users_favorites(); foreach ($favs as $fav){ $list = get_the_title($fav); } return $list; } This snippet shows me the title of the first selected post only. I would like to get a list of all the selected posts, how do I acheive that ? FYI, I am trying to make use of the HOOK provided by gravity forms. You can see the code here. Pleae let me know if I need to be more clear.
If it is a dropdown and you want to populate it with options may be use this filter add_filter("gform_predefined_choices", "add_predefined_choice"); function add_predefined_choice($choices){ $choices["My New Choice"] = array("Choice 1", "Choice 2", "Choice 3"); return $choices; } < gform_field_value_selection filter is for default value. Give a look here < ~~See if this works.. add_filter("gform_field_value_selection", "populate_selection"); function populate_selection ($value) { $favs = wpfp_get_users_favorites(); $list = array(); foreach ($favs as $fav){ $list[] = get_the_title($fav); } return $list; } ~~
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "filters, plugin gravity forms" }
Conditional tag to determine if the user is viewing the Add Media (after clicking Add media button) Is there a WordPress conditional tag for checking if the user is viewing the add media popup after clicking the Add media button? If none, is there an alternative function that can be used? Thanks for any tips and advice.
There are multiple actions available. Demo: add_action( 'upload_ui_over_quota', 'wpse_78085_callback' ); add_action( 'pre-upload-ui', 'wpse_78085_callback' ); add_action( 'pre-plupload-upload-ui', 'wpse_78085_callback' ); add_action( 'post-plupload-upload-ui', 'wpse_78085_callback' ); add_action( 'post-upload-ui', 'wpse_78085_callback' ); function wpse_78085_callback() { # see wp-includes/media-template.php print '<pre>' . current_filter() . '</pre>'; } Result: ![enter image description here](
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "media library, conditional tags" }
Hide content from Post Preview Is it possible to hide content in Post Preview (that is not hidden when the post is published)? I have customised `single.php` quite extensively and there are a few elements that I do not want my authors to load up every time they preview their post.
There is the handy `is_preview` function. So somewhere in your `single.php`. <?php if (!is_preview()) { // Show stuff that doesn't belong on a preview. }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, php, previews" }
How to set where user is redirected to after logging in at wp-login? So i'm fairly certain this probably has something to do with the fact that I'm using a custom role I've set up in my functions.php file with almost 0 permissions. However, I'm still able to access the dashboard, just I get sent to profile.php on login instead of dashboard. I want my user_role to get sent to the dashboard each time as I have a custom widget set up for them there. I can't seem to find the function in the codex and the necessary hook to set this up? It looks like if I was using a custom login form I could use `wp_login_form()` but I just want to use the default login form without hacking the admin file so its not effected by updates. Anyone know the function I'm needing. Cant' seem to feed google the right terminology.
Filter `'login_redirect'`. Sample code, not tested: add_filter( 'wp_login', 'wpse_78150_login_redirect' ); function wpse_78150_login_redirect( $url ) { # uncomment the next line for debugging # var_dump( wp_get_current_user() ); exit; if ( ! current_user_can( 'custom_role' ) ) return $url; return admin_url(); }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "wp admin, wp login form, user roles" }
Is there an action that is called when a post is restored from the trash? I'm looking at the wordpress list of actions and trying to find an action that is called when a post is restored from the trash but cannot find one. Does anyone know if it exists?
There are multiple actions. Listed in order of appearance with their parameters: * `untrash_post` \- `(int) $post_id` // before restoring * `transition_post_status` \- `(string) $new_status, 'trash', (object) $post` * `trash_to_{$new_status}` \- `(object) $post` // useful to address a special trash to status action * `untrash_post_comments` \- `(int) $post_id` // before associated comments are untrashed * `untrashed_post_comments` \- `(int) $post_id` // after associated comments are untrashed * `untrashed_post` \- `(int) $post_id` // after restoring Related answer with more statuses: Execute function when post is published
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "plugins, posts, admin, actions, trash" }
Trying to place shortcode/css/html into an IF conditional statement With the WooCommerce plugin, I'm trying to get a different template/look to apply to the individual product page depending on what category the product is in. In other words, I want a product within the "A" category to have one look, and another product within the "Z" category to have another separate look. I realize there are similar questions asked, and I have used them to try and attempt this myself, but I'm having no luck getting them to work, so I would like to try something different: I need to place the following code: < Inside this IF statement: < Or some kind of similar conditional. So if the product has a category of "z", then echo out the html, css, and shortcode shown in the first pastebin link. If the product is not part of the "z" category then no extra html/css/shortcode is shown.
Instead of getting all terms, looping over them and then searching your array, you can use the `has_term`conditinal tag ex: if( has_term( 'z', 'product_cat',$post->ID ) ) { ?> <div id="post-timer"> <p class="timebuy">Time Left To Buy:</p> <div id="timer-wrap"> <?php echo do_shortcode( '[tminus cid ="12" omitweeks="true" days=" " hours=" " minutes=" " seconds=" "/]' ); ?> </div><!--end timer-wrap--> </div><!--end post-timer--> <?php }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "conditional tags, plugins" }
Change Twenty twelve theme background color I use the twenty twelve theme and I would like to change the background color manually by modifying the right files in the `plugins` folder. However, I can not find what to change in the style.css file. I even tried to modify the background color through the Wordpress interface to #e50000. After that, I looked for a line containing e50000 in my wordpress directory, but there seems to be none. I can't figure out which line to change in my wordpress directory to change the background color.
The background is a option. You can set colors and also images. See in the Administration area, Appearance --> Background !enter image description here !enter image description here Also you can use the Live Preview link on the theme and customize the background and other otpions. !enter image description here
stackexchange-wordpress
{ "answer_score": 5, "question_score": -1, "tags": "css, theme twenty twelve" }
Remove quick edit for custom post type Is it possible to remove the quick edit function for a custom post type? I have 14 custom taxonomy with hundreds of terms in each and it takes too much time and resource to load all of them into the source-code of the page. I tried to find a solution using google but most of them just hides the quick edit button, but the code is loaded in the footer by wordpress, so it doesn't really make any difference.
Check out the Bulk Actions page in the codex. I believe the proper action to unset is inline. This will remove the "Edit" bulk action, which is actually quick edit. <?php function remove_bulk_actions( $actions ){ unset( $actions['inline'] ); return $actions; } add_filter('bulk_actions-custom_post_type_slug','remove_bulk_actions'); ?> As for the Quick Edit in each row, look into manage_{$post_type}_columns, as you may be able to replace the Title column with your own, and render it how you wish. There are currently no filters to remove Quick edit in the WP Posts List Table, so if the replacing of the column does not work, then you will need to create your own WP list table extension (Great tutorial).
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "custom post types, taxonomy, quick edit" }
How i can upload images to another folder? If I go in `Dashboard -> Settings -> Media` I don't see field where I can change upload folder. Is it possible now? For example my website is `myblog.tld`, by default all media content uploads into `wp-content/uploads/year/month`. I want uploads all media to `sub.myblog.tld/year/month` Thanks for advance. PS WP 3.5, Sorry for my english.
In WordPress we can change the default location of the wp-content folder by defining a couple constants in wp-config.php about it here on Codex So if the structure on the server looks like this: /root/ 1. myblog.tld - its own directory 2. sub.myblog.tld - its own directory You can use this in your wp-config.php: define( 'WP_CONTENT_DIR', dirname( $_SERVER['DOCUMENT_ROOT'] ) . DIRECTORY_SEPARATOR . 'sub.myblog.tld' ); define( 'WP_CONTENT_URL', ' It will change the upload dir to the one above the current root (myblog.tld to sub.myblog.tld). And the content-url will be sub.myblog.tld
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "uploads, media settings" }
wp_get_archives() output Iv got this code in my blog.php: <?php wp_get_archives( array( 'type' => 'monthly', 'limit' => 12 ) ); ?> It links to: > /2013/01 My page only loads the header and footer - I think its the main loop - what do I have to do, do I need another file? Or say where to output the code? Thanks..
The `date.php`, `archive.php`, and `index.php` files control the date archive output. You need to check the contents of those files, in respective order, to find the problem. If WordPress can't find `date.php`, it will check for `archive.php`, and load that if found. Otherwise, `index.php` will be used to display date archives. See my answer on a previous question for more information
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, blog, wp get archives" }
Losing all my text and entries on ColorWay Theme I have hosted my website on a ec2. So when the ec2 goes down and I reboot it, I need to change the dns from the old to the new dns (micro instance). Until now I was taking a manual backup of my wordpress page. I tar'ed the /var/www/website files to a tar, and mysqldump of the database to a sql file. And when I need to restore, I do a search replace in the sql file all localhost to that dns (where I am restoring) and untar the tar file to /var/www/website of my new host. But with ColorWay theme, all my settings are lost. I wonder where else will a theme store all its data ? Am I missing something basic here ? Infact any theme, I loose some setting or the other. Sometimes the menu choice, sometimes a few other settings.
> And when I need to restore, I do a search replace in the sql file all localhost to that dns... Doing a find/replace in a text dump of the database will break the serialized data stored in theme options. Use interconnectit.com WordPress Serialized PHP Search Replace Tool to correctly find/replace serialized data. Some simple themes without options don't serialize data, and a find/replace in a text dump is OK; but many themes will break.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "themes, backup" }
post_class remove tag- or category- from slug I've got this in my theme <article <?php post_class('archiveMain'); ?>> But for tags and categories it adds tag- or category- before the slug, any way to remove that? Example: tag-sales would just be sales, category-webinar, just webinar
You can filter `post_class` and change these class names: add_filter( 'post_class', 'wpse_78237_post_class' ); function wpse_78237_post_class( $classes ) { $out = array (); foreach ( $classes as $class ) { if ( 0 === strpos( $class, 'tag-' ) ) { $out[] = substr( $class, 4 ); } elseif ( 0 === strpos( $class, 'category-' ) ) { $out[] = substr( $class, 9 ); } else { $out[] = $class; } } return array_unique( $out ); } But be aware this could result in collisions with other class names, in `body_class` for example. I would not do that.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, tags, post class" }
Force user to login in home page I have a custom login form working properly on my home view. Nice. But what I want is when user try to view some page, be redirected to my home view instead of wp-login. Im trying to do this way: add_action('template_redirect', 'redirect_to_login'); function redirect_to_login(){ if(!is_user_logged_in()){ wp_redirect(home_url()); exit; } } It's not working. Browser says it has too many redirects. What can I do? Thanks!
`template_redirect` is called on every page load including the home page so your code will redirect the user to the homepage even when user is visiting the homepage You could add another condition there, `is_home()` or `is_front_page()`, depending on the setting in admin, but i recommend a longer approach for better compatibility a) Hook into `login_url` to change the url for login. This tells wordpress that login form is present on homepage & `wp-login.php` should not be used add_filter('login_url', 'change_login_url'); function change_login_url() { return home_url('/'); } b) Use `auth_redirect()` which makes sure user is redirected back to the previous page c) Use `wp` hook and not `init` since the conditional is_front_page() will not work as $wp_query global has not been set yet. add_action('wp', 'force_user_login'); function force_user_login() { if(!is_user_logged_in()) auth_redirect(); }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "login, customization" }
Wordpress display image link in shortcode I have a shortcode that display an image when you use the image url inside it. function image_code($atts, $content = null) { return '<img src="'.$content.'" class="user-imgs"/>'; } add_shortcode('img', 'image_code'); So when I use the code like this: [img] it display only the image like this:(in the css I have set the .user-imgs to max-width 600px) <img src=" But I want to display a link to the full image, like this: <a href=" src=" How I can retrieve the image url used in shortcode and use it as a link in to the original image?
You can reuse the `$content` parameter: function image_code($atts, $content = null) { $url = esc_url( $content ); return "<a href='$url'><img src='$url' class='user-imgs' /></a>"; } Or pass the URL as parameter in case you want to use a different URL: function image_code($atts, $content = null) { $args = shortcode_atts( array( 'url' => FALSE ), $atts ); $img = esc_url( $content ); $url = $args['url'] ? esc_url( $args['url'] ) : $img; return "<a href='$url'><img src='$img' class='user-imgs' /></a>"; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "shortcode" }
Override pluggable functions in a plugin? WordPress has a file called `pluggable.php` which contains a list of functions you can override in your plugin. The problem I am facing (I am overriding `wp_authenticate`) is for each blog in my network I try to activate this plugin, I get: > failure, can't re-declare wp_authenticate which was previously declared in pluggable.php This somewhat defeats the ease of use, I have to comment the function in the plugin file, activate the plugin, un-comment the function for it to work properly. What is the correct way to do it? Can't expect users who download plugin to do all that. I am using 3.5 + multi-site configuration
Wrap your function in `if( ! function_exists( 'wp_authenticate' ) )` to get rid of the error and successfully activate your plugin: if( ! function_exists( 'wp_authenticate' ) ){ function wp_authenticate(){} } This is necessary because in the context of activating a plugin, the function _does_ already exist, only after it is activated will your plugin load first and override the original in `pluggable.php`. Plugins are activated in a sandbox to capture any fatal errors which may prevent activation and successful recovery to a working state.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "plugin development, pluggable, activation" }
How can I attach hotlinked images in posts/pages within the same server? Not sure if this makes sense but I'm trying to attach hotlinked images to their posts/pages with no lucky, most plugins such Cache images works ok but only to external domains, I need to auto-attach hotlinked images in the same domain/server. _Addendum_ : This happened duo copying-pasting content from static html files into WP pages and posts. Thanks for any clue!
Thanks @toscho, I think I figured how your code can work (that can take time hahah), firstly import images files within server (Add form server plugin can do this or can use a custom script), find image paths within every post/page that match filenames now in media library, then attach them. I can't use this because there where different imagens but same filenames along different folders (also some problems with filenames using spaces), then I had to use this plugin, you must visit/edit every page/post and download the images, that can be a pain but at least will work with files wherever they are (same doamin for example), surely there is someway to hack this plugin to work on every post on page. (If image filenames has spaces this plugin still will return empty images and you need to re-edit it manually, don't know why WP can diplay hotlinked images with strange filenames)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "images, attachments" }
How to place an image into header.php? I'm trying to customize twentyten theme. this is part of header.php: <body <?php body_class(); ?>> <div id="wrapper" class="hfeed"> <div id="header"> <img id="topL" src="images/img01.png"/> //this img I cannot insert ! </div><!-- #header --> No errors. Simply - nothing happens.
Don't use a relative URL. If you look at the source you are probably trying to load the image from ` when what you likely want is ` Assuming the image is in the theme directory in a folder that shares a directory with `style.css`, do this: <img id="topL" src="<?php echo get_stylesheet_directory_uri(); ?>/images/img01.png"/> <
stackexchange-wordpress
{ "answer_score": 3, "question_score": -2, "tags": "images, headers" }
The inner mechanism of WP SEO plugins This is more of a conceptual question, but it has actual ramifications. Going through the various SEO plugins I found nowhere a PHP tag that should be embedded in the actual HTML page and echo the meta data. How does it work then? Simply saving it to the DB doesn't seem enough. What is the mechanism through which the plugin "injects" the SEO data to the page?
In case you are talking about adding meta tags and changing the title they rely on `wp_head` action being fired at theme header before the `</head>`tag is generated. For changing the title they probably use the `wp_title` filter. Older versions of "all in one seo" used to buffer the head section and replace the title tag in something like add_action('init','start_buf'); function start_buf( { ob_start(); } add_action('wp_head','end_buf'); function end_buf() { $head = ob_get_contents(); $head = string replace '<title>....</title>' in $head with the configured title ob_end_clean(); echo $head; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "seo" }
Remove Actions added by SEO ultimate Plugin I am trying to remove the action hooks added by SEO ultimate plugin for some pages. The way it is added in the plugin's class is //Hook to output all <head> code i changed the priority to 2 add_action('wp_head', array(&$this, 'template_head'), 2); The SEO plugin creates a global variable like this global $seo_ultimate; $seo_ultimate =& new SEO_Ultimate(__FILE__); In my plugin, i try removing it by add_action('wp_head',array($this, 'remove_seo_header'),1); } function remove_seo_header() { remove_action('wp_head', array($seo_ultimate,'template_head')); } But it does not remove the action. Can anyone point out where am I wrong?
You have to use the same priority, and you need access to the global variable: function remove_seo_header() { remove_action( 'wp_head', array( $GLOBALS['seo_ultimate'], 'template_head' ), 2 ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "filters" }
How to change tag Title to its name? i have previously asked it in stackoverflow, but there was no answer! I wish to change the title of Tags pages of my wordpress blog. What I want to do is to keep the Tag name as it's title only. For example: If a tag name is "Wordpress Tag Pages Tutorial" then that tag should have the same title "Wordpress Tag Pages Tutorial" instead of "Blog Name - Wordpress Tag Pages Tutorial" so what to change in this code? I have tried but showing errors like only variables name in wordpress title. <title> <?php if (is_home () ) { bloginfo('name'); }elseif ( is_category() ) { single_cat_title(); echo ' - ' ; bloginfo('name'); } elseif (is_single() ) { single_post_title();} elseif (is_page() ) { bloginfo('name'); echo ': '; single_post_title();} else { wp_title('',true); } ?> please see this screen-cast i.stack.imgur.com/Ai9JU.png
Use … if ( is_tax( 'post_tag' ) ) echo single_term_title(); I would just call a naked `wp_title()` and change that title per filter. See example 1, 2 and 3.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "tags, title" }
How to reorder billing fields in WooCommerce Checkout template? I'm creating a madlib style checkout form using WooTheme's _Customizing checkout fields using actions and filters_. Billing fields in the checkout template `form-billing.php`are displayed with this call: <?php foreach ($checkout->checkout_fields['billing'] as $key => $field) : ?> <?php woocommerce_form_field( $key, $field, $checkout->get_value( $key ) ); ?> <?php endforeach; ?> How can change the order the fields appear? The current (default) field order is: first name last name company (hidden for me) town/city zipcode country state email phone _Default order:_ !screenshot I want the fields to be in a more natural order for Americans (where I live), so: first name last name company (hidden for me) town/city state zipcode country email phone How can I best do this?
Thanks to Dbranes for the answer. Replace: <?php foreach ($checkout->checkout_fields['billing'] as $key => $field) : ?> <?php woocommerce_form_field( $key, $field, $checkout->get_value( $key ) ); ?> <?php endforeach; ?> With: <?php // order the keys for your custom ordering or delete the ones you don't need $mybillingfields=array( "billing_first_name", "billing_last_name", "billing_company", "billing_address_1", "billing_address_2", "billing_city", "billing_state", "billing_postcode", "billing_country", "billing_email", "billing_phone", ); foreach ($mybillingfields as $key) : ?> <?php woocommerce_form_field( $key, $checkout->checkout_fields['billing'][$key], $checkout->get_value( $key ) ); ?> <?php endforeach; ?>
stackexchange-wordpress
{ "answer_score": 6, "question_score": 15, "tags": "filters, plugins" }
How to change post status in hook? I have similar problem as described in How to trap "Publish" button to check for meta box validation? Answer there is to hook into `save_post` and change post type. How can I do it? I try to use `wp_transition_post_status` but it doesn't work for me... function myHook( $post_ID, $post ) { wp_transition_post_status('pending', $post->post_status, $post ); } add_action( 'save_post', 'myHook', 10, 2 ); Edit: I have clear wordpress installation without any plugins, additional code and similar
You get the full post object as a second parameter on `save_post`. Use it to change the status just like the following code. add_action( 'save_post', 'wpse_78351_status', 10, 2 ); function wpse_78351_status( $post_ID, $post ) { remove_filter( current_filter(), __FUNCTION__ ); if ( 'trash' !== $post->post_status ) //adjust the condition { $post->post_status = 'draft'; // use any post status wp_update_post( $post ); } } See this answer for a list of post statuses.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "plugin development, publish, post status" }
Remove Spaces From WP_LINK_PAGES By default, wp_link_pages (the code which allows you to breakup posts into multiple pages) creates spaces between each number. Is there a way to remove these spaces via functions.php?
Just replace `a> <a` with `a><a`: echo str_replace( 'a> <a', 'a><a', wp_link_pages( array ( 'echo' => FALSE ) ) ); If you want to remove the spaces around unlinked numbers too, I suggest a separate function in your theme’s `functions.php` to keep the code readable: function trimmed_link_pages( $args = array () ) { $args['echo'] = FALSE; $links = wp_link_pages( $args ); $links = str_replace( array ( 'a> ', ' <a', ':<a' ), array ( 'a>', '<a', ': <a' ), $links ); print $links; } Use it like `wp_link_pages()`: if ( have_posts() ) { while ( have_posts() ) { the_post(); print '<h2><a href="' . get_permalink() . '">' . get_the_title() . '</a></h2>'; the_content(); trimmed_link_pages(); } } Related: Changing Link Attributes for Wp_Link_Pages.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp link pages" }
Is Wordpress Suitable for my site? I will be starting the development of a site that will allow my users to upload pictures and giving the ability to other people to view them. I just want to know if wordpress is suitable for all these things (payment system, editing the user profiles) because i hear all the time that wordpress is mostly for blogs, but my site has nothing to do with a blog. Thanks in Advance!
This is probably mostly a preference thing, but I don't think Wordpress is a great solution for sites outside of content creation. In my opinion, one of the weakest parts of Wordpress is how they handle images and galleries. We are building a completely custom interface for creating galleries on our application because it's so cumbersome. In addition to just photo/gallery management, payment systems are all handled through 3rd party plugins. So they are fairly cumbersome in themselves. In my opinion, from what you've explained Wordpress is probably not the right choice, but there are tons of other options like joomla and drupal.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp admin" }
How can I find the first post in a category that has a featured image and then return the get_the_post_thumbnail()? I have a function that I thought should find the first article with a featured image in it, and then return that image. Not sure if this is the best way to go about it, as it's giving me a 502 Bad Gateway... function get_category_post($cat_id){ $finished = false; $postcount = 0; $post_args = array( 'numberposts' => 1, 'category' => $cat_id, 'fields' => 'ids' ); $posts = get_posts($post_args); while ( $finished != true ) { if ( has_post_thumbnail($posts[$postcount]) ) { $postthumb = get_the_post_thumbnail($posts[$postcount], $size = 'thumbnail'); $finished = true; } $postcount++; } return $postthumb; }
The ID of the featured image is stored under the meta key `_thumbnail_id`, so we can do a query for a single post that has this key: $args = array( 'posts_per_page' => 1, 'meta_key' => '_thumbnail_id', 'cat' => $cat_id ); $latest_thumb = new WP_Query( $args ); if( $latest_thumb->have_posts() ) return get_the_post_thumbnail( $latest_thumb->post->ID );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "post thumbnails" }
How can I do a url redirect to include a wordpress username? I currently have a button like this, that takes a user to their 'mentions' page <a href=" global $userdata; get_currentuserinfo(); echo( $userdata->user_login );?>">button</a> What I'd like instead is that a user can see their 'mentions' when they log in to the page. so I'd like admin to be redirected to < when he goes to a particular page (i.e. the homepage) - I think this would be best using a PHP redirect? How could I do this?
You have to add action to, for example, `template_redirect` action hook. The action would perform your desired checks and redirect user using the `wp_redirect()` function. The code could look something like this: function my_redirect_function() { // Check if home page is being displayed if ( is_home() ) { global $userdata; get_currentuserinfo(); $username = $userdata->user_login; $url = ' . $username; wp_redirect( $url ); exit; } } add_action( 'template_redirect', 'my_redirect_function' ); You place whatever checks (such as conditional tags) you'd like instead of `is_home()` check.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "users, redirect, urls" }
Add file while inserting post Is it possible while adding post through wp_insert_post also upload images to this post from url.
You can attach images to a post from URI via the `media_sideload_image` function: $post = array(); // your post data $post_id = wp_insert_post( $post ); $url = " $desc = "The WordPress Logo"; $image = media_sideload_image( $url, $post_id, $desc );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "wp insert post" }
Where is the changelog for 3.5? where is the list of added removed files? This: < is not a changelog. This: < gives a few changes, etc, but no list of files added and removed. Where might I find a list of 'breaking changes'? Actions and Filters that work differently?
You can always use GitHub. WordPress has an official (view-only) GitHub repository, and GitHub has an excellent comparison feature. Here's the GitHub comparison of WordPress 3.4.2 vs 3.5.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "filters, codex, wordpress version" }
Subscribe to a post's comments without posting a comment yourself I've seen a few plugins (subscribe2, subscribe to comments) that allow people that have commented to receive emails containing follow up comments. What I want to do is slightly different. I want to post to have a 'Subscribe' button. Clicking this would then allow the user to receive by email subsequent comments to that post. They would not need to post a comment themselves. Is this possible with a plugin, code or a mix of the two?
Subscribe To Comments Reloaded allows subscribing without commenting. It uses a link instead of a button, though. Screen shot: > !enter image description here It shouldn't be too hard to customize.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "comments, email, notifications, subscription" }
Admin user can't update WP I have a site running WP 3.3.2. The backend shows a bar saying "WordPress 3.5 is available! Please notify the site administrator." Funny thing is that I'm logged in with an admin user, I double checked that. When trying to access the update page (at wp-admin/update-core.php) I get this error: "You do not have sufficient permissions to access this page." Any hints on what could be going on here? Thanks.
Try to make a new admin user in the db. Follow these steps you should be able to create a new admin user, then update and then you can give your old user admin rights again. Or use the new user. Your old user might have wrong setting in the DB <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 19, "tags": "updates" }
Get all taxonomy posts by id I have this code that should return all the posts that related to the taxonomy id, but it returns the last 5 posts. <?php $leaderships = new WP_Query(array( 'post_type' => 'posttype', 'posts_per_page' => 11, 'tax_query' => array( array( 'taxonomy' => 'taxonomy-name', 'field' => 'id', 'terms' => 13, ), ), )); ?> posts_per_page is not working here, Any help to get all the posts. Thanks
Thanks every one for help, I discovered that that the problem is from my theme admin that was limiting the posts to 5 and fixed now.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom taxonomy" }
How to access my site using IP Address? I would like to know how to access my website using Ip address instead of domain. Like 173.252.100.16 can used to access facebook. My Website is: www.jijojose.me Server have multiple websites hosted.
Open a Terminal or CMD and type `ping www.jijojose.me` then press Enter. The IP address listed it's the server's IP address. However You won't be able to access you website this way (e.g. ` unless: 1. You know the folder where it is located on the server, and your server has `mod_userdir` or similar extension enabled for the web server. 2. The server it's configured to show by default your website when no valid `host` header is specified.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "ip" }