INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Author bio Social Links I'm using simple code to show user social link in author bio. **in functions.php** <?php function add_remove_contactmethods( $contactmethods ) { // Add Twitter $contactmethods['twitter'] = 'Twitter'; //Add Facebook $contactmethods['facebook'] = 'Facebook'; // Remove Contact Methods unset($contactmethods['aim']); unset($contactmethods['yim']); unset($contactmethods['jabber']); return $contactmethods; } add_filter('user_contactmethods','add_remove_contactmethods',10,1); ?> **in single.php** <a href="<?php the_author_meta('twitter'); ?>" title="Twitter" target="_blank" id="twitter"><img src="/images/twitter.png" alt="Twitter" /></a> so how can i hide social link in author bio when the field is empty in user profile. please help me...
You need to check, if the field is empty or not before printing link using the get_the_author_meta function. <?php if(!empty(get_the_author_meta('twitter'))) { ?> <a href="<?php the_author_meta('twitter'); ?>" title="Twitter" target="_blank" id="twitter"><img src="/images/twitter.png" alt="Twitter" /></a> <?php } ?> or, try <?php if(!empty(get_user_meta(get_the_author_meta('ID'),'twitter'))) { ?> <a href="<?php the_author_meta('twitter'); ?>" title="Twitter" target="_blank" id="twitter"><img src="/images/twitter.png" alt="Twitter" /></a> <?php } ?> but, for some reasons, followed code fixed it <?php if(strlen(get_the_author_meta('twitter')) >5) { ?> <a href="<?php the_author_meta('twitter'); ?>" title="Twitter" target="_blank" id="twitter"><img src="/images/twitter.png" alt="Twitter" /></a> <?php } ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "author, customization" }
Best way to abort plugin in case of insufficient PHP version? You write a plugin which requires PHP 5.1. Someone tries to install it on a server with PHP 4. How do you deal with that in a safe and user-friendly manner?
/** * Plugin Name: Foo */ // Check for required PHP version if ( version_compare( PHP_VERSION, '5.1', '<' ) ) { exit( sprintf( 'Foo requires PHP 5.1 or higher. You’re still on %s.', PHP_VERSION ) ); } // The rest of your plugin code follows I'm not sure since which WP version this happened, but in 3.5 the plugin actually fails to activate and the error message is shown to the user in the admin, which is neat. The error message is not translated, though. In order to do that you’d have to load your translation files right before the `exit` call.
stackexchange-wordpress
{ "answer_score": 10, "question_score": 15, "tags": "plugin development, customization" }
A single category with a specific permalink structure differing from the standard set for the rest of the site I'm interested to know if there's a method to specify a specific link structure for only a single category. Currently I have my install set to **/2012/12/post-title**. However there is a single category I would like to set to **/category-name/post-id/**. Part of this is that I don't plan to title any of these posts, but I also would like to make it simple to block this section from being crawled using the _robots.txt_ file. _Possible caveat, I'm using Nginx rather than Apache, so rewrite rules if needed will differ._ Thanks
You can use URL rewrites to edit the displayed URL, but without changing your actual wordpress setup all your internal links will still point to the structure assigned in your permalinks settings. The most straightforward way to do this would be by using a custom post type. With CPTs you can set up a whole different structure for your posts and get as customized or as standard as you want with how wordpress handles it, both internally and externally. You can even make custom taxonomies (post categories is an example of a taxonomy) and associate it only with that CPT. You can do this manually by editing your functions.php file (good tutorial here) or use a plugin like this one to do the heavy lifting for you. Here's the codex for registering CPTs I've recently gotten pretty deep into custom post types, use role creation and management and such. It's really powerful and will save you a lot of hassle with URL rewrites.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "categories, permalinks, nginx" }
Two WordPress sites sharing the same content My question is this: Is it possible to have two separate installations of WP with two separate domains sharing the same content? **Scenario:** User on < publishes a post. < uses the exact same database and can show that post as if it was its own. I've been looking around for quite some time for this solution and cannot find a valid procedure to achieve this. **My ideas are:** 1. Is there a way to share the database without having the issue of the siteurl and theme stored in the database be an issue. 2. Maybe use just an RSS feed and somehow parse the XML and display them in a template. This is not the best idea because it would have zero functionality that WordPress provides. 3. Find a way to somehow sync the databases but exclude the wp_options table ?
If your main requirement is to synchronise blog posts from a master site to a slave, then maybe look at the FeedWordPress plugin. It means that you would only add/edit posts on one website and they would be replicated to the other site. That will allow you to cleanly run different plugins on the two sites.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 8, "tags": "database, sharing" }
add_filter on "the_excerpt" only works when post does not have excerpt class my_menu extends WP_Widget { function widget($args, $instance) { // Excerpt length filter $new_excerpt_length = create_function('$length', "return " . $excerpt_length . ";"); if ( $instance["excerpt_length"] > 0 ) { add_filter('excerpt_length', $new_excerpt_length, 999); } //... } } This filter works great if the post does not have an excerpt. How do I apply the same filter to a post that has an excerpt? In other words, when the post has an actual excerpt, its not filtering it at all, the whole excerpt is displayed. However, when the post does not have an excerpt, the get_the_excerpt() call gets filtered so that it only returns the number of words specified by "excerpt_length"
I posted an article about this a while ago: function wp_trim_all_excerpt($text) { // Creates an excerpt if needed; and shortens the manual excerpt as well global $post; $raw_excerpt = $text; if ( '' == $text ) { $text = get_the_content(''); $text = strip_shortcodes( $text ); $text = apply_filters('the_content', $text); $text = str_replace(']]>', ']]&gt;', $text); } $text = strip_tags($text); $excerpt_length = apply_filters('excerpt_length', 55); $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]'); $text = wp_trim_words( $text, $excerpt_length, $excerpt_more ); return apply_filters('wp_trim_excerpt', $text, $raw_excerpt); } remove_filter('get_the_excerpt', 'wp_trim_excerpt'); add_filter('get_the_excerpt', 'wp_trim_all_excerpt');
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "filters, excerpt" }
Theme Activation, Create Database Tables I have been tasked with creating a theme that will be a base to list the site owners ebay store products. I have fleshed most of the project out in plain old php to get everything working as regards to adding the listings via the ebay api, right now im integrating the code into functions.php of the custom theme. What i need to do is create database tables in WP to hold the ebay xml file values from various xml files, following the codex i can see how it is done via plugin activation, My question is how can i do it directly via the themes functions.php on theme activation following the codex it does not work which im guessing is down to require_once ABSPATH
In functions.php you can create "your_set_tables_function()" and then hook it in the "after_switch_theme" hook. Example: add_action("after_switch_theme", "your_set_tables_function");
stackexchange-wordpress
{ "answer_score": 11, "question_score": 2, "tags": "themes, database, customization" }
Count posts published in one particular day: the lighter way I would like to get just the number of posts published in one particular day. I'm using this code, but this retrieve lot of code: $day = date('Ymd'); $query01 = array('numberposts' => -1, 'post_type' => array('post', 'video', 'image', 'review'), 'm' => $day); $mypost = get_posts($query01); $counter = count($mypost); wp_reset_postdata(); Is there a lighter way to obtain the same?
`$wp_query->found_posts` can be used to get the number of posts. But here are arguments you can use to optimize the query and avoid useless SQL retrievals: cache_results' => false, // Turns off post caching 'no_found_rows' => true, // To optimize when pagination is not required 'fields' => 'ids' // To only retrieve IDs information, nothing else (avoid collecting all useless post data) If you have more optimizing tips for simple queries, I would be happy to hear about them
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "count" }
Show category children, one level I am coding a pretty complex wordpress site (at least, taxonomically speaking), and i need to display a list of categories, children of a parent category, but I am struggling with getting the code to do this. I tried doing something like: <?php $cat = get_query_var('cat'); $categories= get_categories('hide_empty=0&parent=1&child_of='.$cat); foreach ($categories as $category) { $mycat .= $category->cat_name; echo $mycat; } ?> But i don't seem to get the correct output. Do you have any idea? Thx!
Why are you using the parameter parent=1? If you remove this parameter it should work. If you want children and grandchildren, you should use: $categories = get_categories('hide_empty=0&child_of='.$cat); If you want only direct children, you should use: $categories= get_categories('hide_empty=0&parent='.$cat); Also note that you are echoing $mycat inside the loop, and you are joining the multiple categories in this var, so the categories should appear repeated...
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "categories" }
What is <# code #> in media-template.php, and how does it work? I'm checking `/wp-includes/media-template.php` and just found this: <# if ( data.compat && data.compat.meta ) { #> {{{ data.compat.meta }}} <# } #> Never seen `<# #>` or `{{{ }}}` before. What kind of PHP is this? Searching for this symbols in Google seems futile...
Those are javascript templates that get compiled into HTML by a javascript library. I think WP uses underscore.js. Let's say you write a jQuery plugin, and you have to append HTML code to the document. Using such templates you can avoid stuffing that HTML code inside huge concatenated strings within your javascript code, and put it where the other HTML markup is. So you load that template from your plugin, compile it (variables get replaced) and append the resulting HTML to your document. Essentially you separate the business logic from the presentation logic. This also makes your plugin more decoupled.
stackexchange-wordpress
{ "answer_score": 9, "question_score": 9, "tags": "php, core" }
undefined index I upgraded to the latest version of WordPress and now for some reason when I go to the menus page and it only seems to happen there, I get an error saying Notice: Undefined index: eventmeta_noncename in /home3/themes/savior/functions.php on line 1399 Here is the code. Line 1399 would be line 4 in the code < I can't figure out why it's an undefined index.
This seems to have solved the issue.. Checking to see that it is set. if ( !isset( $_POST['eventmeta_noncename'] ) || !wp_verify_nonce( $_POST['eventmeta_noncename'], plugin_basename(__FILE__) )) { return $post->ID; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "errors" }
$wpdb->prepare() warning in WordPress 3.5 I am receiving this warning when I try to run a database query: > **Warning:** Missing argument 2 for wpdb::prepare() The offending query is: $result = $wpdb->get_var( $wpdb->prepare( "SELECT DISTINCT meta_value FROM $metatable WHERE meta_key LIKE '%matchme%' AND meta_value IS NOT NULL AND meta_value <> ''" ) ); Is there a way to remove the error by modifying the above query?
Remove the call to `$wpdb->prepare()`: $result = $wpdb->get_var( "SELECT DISTINCT meta_value FROM $metatable WHERE meta_key LIKE '%matchme%' AND meta_value IS NOT NULL AND meta_value <> ''" ); In this case, the `$wpdb->prepare()` function is **not doing anything**. There are no variables holding unknown values, therefore there is no need to sanitize them. If you _did_ have variables that need sanitizing, you can add a second argument to the function: $result = $wpdb->get_var( $wpdb->prepare( "SELECT DISTINCT meta_value FROM %s WHERE meta_key LIKE '%matchme%' AND meta_value IS NOT NULL AND meta_value <> ''", $metatable ) ); **Relevant links:** * PHP Warning: Missing argument 2 for wpdb::prepare() * Ticket #22873: Consider moving to a notice for $wpdb->prepare in 3.5.1
stackexchange-wordpress
{ "answer_score": 6, "question_score": 5, "tags": "database, errors, wpdb" }
Wordpress plugin updates / set file as immutable to prevent certain files from changing? I'm wondering--what is the best way to prevent a file (say, a custom CSS file associated with a plugin) from being overwritten during the update process? Would setting the file's status as immutable do the trick, or would this just cause an error during update? What is the best way to go about doing this?
Basically you should not include the file in the plugin in the first place. If the reason you don't want it to be overwritten is because you modify it based on some local setting, then you should leave the immutable part of the file in it and create another file which will contain the mutable parts. Then you can use your CSS like that (assuming you suplly constant.css with the plugin and generate costum.css locally. add_action('wp_head','my_plugin_addcss'); function my_plugin_addcss() { // register and enqueue the immutable part wp_register_style('constantStyle', WP_PLUGIN_URL . '/my_plugin/constant.css'); wp_enqueue_style('constantStyle'); // register and enqueue the custom part wp_register_style('costumStyle', WP_PLUGIN_URL . '/my_plugin/costume.css'); wp_enqueue_style('costumStyle'); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, updates" }
Disable gallery in 3.5 media iframe I'm creating a setting to set a logo. It works but there is a problem. I only need one image to be set so the gallery item should be disabled / hidden. Of course this should only effect this page, of even better this setting. <?php // above this I do a simple settings api ?> <input id="set_logo" type="text" size="100" name="set_logo" value="<?php echo esc_attr( $value ); ?>" /> <?php do_action( 'media_buttons', 'set_logo' ); I've looked in multiple places in code but I can't find any clues how to do this. **EDIT** I've solved it in a different way that is not related to this. The solution is now implemented in my first plugin: < _shameless plug._
You can disable tabs using a filter hook. Replace wpse_76095_isOurMediaUpload() with however you determine that you're running the media popup. add_filter('media_upload_tabs', 'wpse_76095_filterMediaUploadTabs'); /** * filter out unwanted media upload tabs * @param array $tabs * @return array */ function wpse_76095_filterMediaUploadTabs($tabs) { if (wpse_76095_isOurMediaUpload()) { unset( $tabs['type_url'], // no linking from external sites (no local image) $tabs['gallery'], // no galleries $tabs['nextgen'] // no NextGEN galleries ); } return $tabs; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "uploads, gallery" }
How can I change Max Embed Size in WordPress 3.5? after updating to WordPress 3.5 my automatic embeds are limited to a width of 500px, and the settings for this size have been removed with WordPress 3.5 Also, I can't find the Values in the `wp_options` table. Does anyone know how to change them again? Cheers, fischi
See the function `wp_embed_defaults()` in `wp-includes/media.php`: function wp_embed_defaults() { if ( ! empty( $GLOBALS['content_width'] ) ) $width = (int) $GLOBALS['content_width']; if ( empty( $width ) ) $width = 500; $height = min( ceil( $width * 1.5 ), 1000 ); return apply_filters( 'embed_defaults', compact( 'width', 'height' ) ); } To change these values filter `embed_defaults`: add_filter( 'embed_defaults', 'wpse_76102_new_embed_size' ); function wpse_76102_new_embed_size() { // adjust these pixel values to your needs return array( 'width' => 1000, 'height' => 600 ); }
stackexchange-wordpress
{ "answer_score": 10, "question_score": 7, "tags": "embed, media settings" }
Change the default-view of Media Library in 3.5? When inserting media into a post, is there a way to change the default-view of the Media-Library from "All media items" to "Uploaded to this post"? !borrowed Screenshot There is another thread where this question was extracted from: How to manage attachment relationships
There were two minor mistakes in my previous answer: 1. I forgot to trigger the `change` event for the parent. 2. I called the function on every AJAX call, making other selections impossible. Here is the fixed code: <?php /** * Plugin Name: Pre-select post specific attachments */ add_action( 'admin_footer-post-new.php', 'wpse_76048_script' ); add_action( 'admin_footer-post.php', 'wpse_76048_script' ); function wpse_76048_script() { ?> <script> jQuery(function($) { var called = 0; $('#wpcontent').ajaxStop(function() { if ( 0 == called ) { $('[value="uploaded"]').attr( 'selected', true ).parent().trigger('change'); called = 1; } }); }); </script> <?php }
stackexchange-wordpress
{ "answer_score": 22, "question_score": 35, "tags": "media library" }
Dropdown menu on click change Im working on a website where I need to create a submenu that shows only the parent pages. When I click on one of the parents it has to show the children from that parent. Here is the menu hierarchy I used this widget plugin: Subpages Extended for showing the parents and children: * Parent * Parent1 from parent * Child1 from parent1 * Child2 from parent1 * Parent2 from parent * Child1 from parent2 * Child2 from parent2 Could you explain me or give an example/tutorial on how to do it? Thanks..
I think you don't have to use any plugin for that, check out: < and use `$depth` to control the levels you want to display.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, menus, javascript, dropdown" }
Linking to page with all posts I'm new to the Wordpress world. I've read the template hierarchy document and read online, but, I wanted to get feedback from here on what the best way to do this would be. What I'm trying to do is create a page that simply lists all of the posts that my site has. I am creating my own theme and as a result the home page (front-page.php) is highly tweaked. I do list recent posts, but, only their titles. On my home page I would like to add a link to "See all blog posts". I'm comfortable with the PHP code; I know how to display posts. I'm just not sure what the best way to get a page that lists them all aside from the homepage is. I'm sure this is very easy to accomplish, I'm just still working through the Wordpress structure so your advice is appreciated!
You have to create a page template with Loop inside. Then create a page "All My Posts" and assign the template you've created to it in "Page Attributes" section of "Edit Page" admin page. You can link to this page from the Front Page using `get_page` function. Function Reference/get page.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "posts, links, homepage" }
Prevent network activation of plugin I have a plugin that currently doesn't support network activation. The best fix for this of course is to fix it :) which I plan to do. However I wonder if there is a temporary solution I can use to prevent network activation in the meantime, perhaps a workflow similar to: 1. Detect if the activation is network-wide (how??) 2. Display message that it's currently not supported, and I stink, I'm sorry 3. Interrupt the activation or deactivate Or, other suggestions accepted. Thanks. For clarification: Multisite activation is fine, just not network-wide activation.
The answers here are overthought and too complex. Why deactivating the plugin instead of preventing activation? Something as simple as calling die('your error message here) upon activation will do the job. function activate($networkwide) { if (is_multisite() && $networkwide) die('This plugin can\'t be activated networkwide'); } register_activation_hook('your-plugin/index.php','activate'); Then when you try to activate in the panel, you will get a nice error on top of the page, with your error message.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 9, "tags": "plugin development, multisite, activation" }
should i use GLOB_ONLYDIR to hook add-ons for wordpress plugin I am adding the ability to add add-on to my plugin. Right now i am using: foreach(glob(GMW_PATH .'/plugins/*', GLOB_ONLYDIR) as $dir) { include_once $dir . '/connect.php'; } The function loop trough all the folders inside the "plugins" folder in my plugin and includes the connect.php file that is inside each of those folders (each add-on folder include the connect.php file). This is the first time i am using GLOB_ONLYDIR and i am not sure about its performance. Is it a good idea to use the above or should i create each add-on as a stand alone plugin, which they actually are, but add the a ability to just activate them from the plugins page? Thank you.
Depends on your plugin. I prefer to use plugins with the minimal functionality that meets my needs. Less configuration options, less documentation to read, and hopefully less bugs. You also need to think on the upgrade process. If you make a change in a big plugin I should look into upgrading it even if the change is in a functionality I don't use, and upgrades are always risky or take time to test. Therefor, if you can break up your functionality into several plugins, that is the way to go IMO. But if it is not possible for what you do, then before you think about distributing addons for your plugin, think how are they going to be installed and upgraded. Unless you have a good plan for managing the addons I suggest you distribute them with the main plugin and then you can directly include them without the need for `GLOB_ONLYDIR`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, performance" }
Remove "Insert from URL" link in Media upload - WP 3.5 How do I remove the `Insert from URL` link in the new Wordpress 3.5 Add Media popup page? In earlier versions of Wordpress, this worked fine: // removes URL tab in image upload for post function remove_media_library_tab($tabs) { if (isset($_REQUEST['post_id'])) { $post_type = get_post_type($_REQUEST['post_id']); if ('premium' == $post_type) unset($tabs['library']); unset($tabs['type_url']); } return $tabs; } add_filter('media_upload_tabs', 'remove_media_library_tab'); Who knows?
This should work: add_filter( 'media_view_strings', 'cor_media_view_strings' ); /** * Removes the media 'From URL' string. * * @see wp-includes|media.php */ function cor_media_view_strings( $strings ) { unset( $strings['insertFromUrlTitle'] ); return $strings; }
stackexchange-wordpress
{ "answer_score": 6, "question_score": 7, "tags": "php, functions, filters, media, media library" }
Display three different levels of navigation from wp_nav_menu separately? I have a three level nav setup using Wordpress menu creator. Structure: A —1 ——Y ——Z —2 —3 B C I wish to display each level of the navigation alone, in different areas of the page. With current items highlighted. On pages A, B or C I want to display: A B C (I can use wp_nav_menu with depth=1 for this) On pages 1*, 2 or 3 I want to display: A B C and 1 2 3 On pages 1*, Y or Z I want to display: A B C, 1 2 3 and Y Z Are there any easy ways of displaying the second and third level navs for the currently selected menu item? The important thing is that I need to be able to display each "level" menu individually. Thanks
What I ended up doing was setting up three sidebars, each using an instance of Advanced Menu Widget and settings as follows: Sidebars 1\. main nav: start at level 0, display 1 level deep, display all items 2\. second level nav: start at level 1, display 2 level deep, only show strictly related sub items 3\. third level nav: start at level 2, display 3 level deep, only show strictly related sub items This gives me pretty much the control I needed.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "menus" }
Count posts in custom taxonomy Is there a way to count all published posts from a custom taxonomy? While looking around I found this snippet but I didn’t manage to get it to work … global $wpdb; $query = " SELECT COUNT( DISTINCT cat_posts.ID ) AS post_count FROM wp_term_taxonomy AS cat_term_taxonomy INNER JOIN wp_terms AS cat_terms ON cat_term_taxonomy.term_id = cat_terms.term_id INNER JOIN wp_term_relationships AS cat_term_relationships ON cat_term_taxonomy.term_taxonomy_id = cat_term_relationships.term_taxonomy_id INNER JOIN wp_posts AS cat_posts ON cat_term_relationships.object_id = cat_posts.ID WHERE cat_posts.post_status = 'publish' AND cat_posts.post_type = 'post' AND cat_term_taxonomy.taxonomy = 'YOUR-CUSTOM-TAXONOMY' AND cat_terms.slug IN ('TERM-SLUG-1, TERM-SLUG-2') "; return $wpdb->get_var($query);
Use an instance of **WP_Query** to query the database. < To query database for custom taxonomies use, $query = new WP_Query( array( 'people' => 'bob' ) ); For more details on available options see: **Taxonomy Parameters** < Retrieve published posts using 'post_status' => 'publish' Use `found_posts` to retrive the number of posts $count = $query->found_posts;
stackexchange-wordpress
{ "answer_score": 9, "question_score": 11, "tags": "custom taxonomy" }
Where can you find the available filter tags? In my attempt to alter navigations current-menu-item class, I found a possible solution < , add_filter('nav_menu_css_class', 'my_css_attributes_filter', 100, 1); He makes use of a filter who is called with a tag 'nav_menu_css_class' , But it got me wondering, where can you find information about what filters are available to use? < does not mention anything about filters...
There are multiple was to find filters: 1. Use an IDE (see Eclipse example), set WordPress as a separate project and search in this project for `apply_filters` or `do_action`. 2. Get a program to search in all files of a directory (grep, Notepad++) and do the same search with that. 3. Read the source code. If you start with `wp_nav_menu()` and follow the functions called in its definition you will find the filters and actions you need.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "filters, tags" }
Disable directory browsing of uploads folder I'm using Wordpress as a CMS for a simple website. I want to prevent users from being able to browse the directories such as the wp-content/uploads folder or any directories of my theme. My host does not allow me to use "Options" or "DirectoryIndex" within a .htaccess file. I have tried putting a .htaccess file in the /uploads/ folder with "IndexIgnore *" in it. However none of my images from the /uploads/ folder will show up on my site with that option. I also tried password protecting the directory with a .htpasswd file but this gives any visitor of my site a popup asking them to enter the credentials. So my question is how do I prevent people from browsing the directories while enabling me to embed files from those directories in my wordpress posts/pages. For example, can I place .htaccess file in the /uploads/ directory and add RewriteRules so WordPress can still show the files on my website?
To disable directory browsing all you have to do is drop in a blank `index.html` file into the `wp-content\uploads` directory, each subsequent sub-directory also would need a blank index file, there are plugins that can automatically do this for you. ps. Get a better host, there is no reason they should disallow you having your own .htaccess files.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "htaccess, security, directory" }
How do I use WP_query with multiple post IDs? I want to query multiple posts with an array of IDs (note: I am querying a custom post type). Here's what I have, which isn't working: $myarray = array(144, 246); $args = array( 'post_type' => 'ai1ec_event', 'p' => $myarray ); // The Query $the_query = new WP_Query( $args ); Any tips on how to do this?
Please reference the Codex entry for post/page parameters for `WP_Query()`. The `'p'` parameter takes a single post ID, as an integer. To pass an _array_ of posts, you need to use `'post__in'`: $myarray = array(144, 246); $args = array( 'post_type' => 'ai1ec_event', 'post__in' => $myarray ); // The Query $the_query = new WP_Query( $args );
stackexchange-wordpress
{ "answer_score": 45, "question_score": 23, "tags": "php, wp query" }
How do I programatically remove Menus? I know that each menu item is simply post present in `nav_menu_item` post type. It has has ID and can be removed with `wp_delete_post()` but posts deleted this way don't remove menus present under [Appearance > Menus]. Only menu items are removed. For instance I have "My Menu" under [Appearance > Menus] that has the following items: page-1, page-2, category-3. I can remove menu items with `wp_delete_post()` but "My Menu" (group for those items) remains intact. How can I programatically remove all defined Menus (and menu items)?
Please check wp_delete_nav_menu() function. If you want to get all nav menus you can check wp_terms table or $menu_list = get_terms('nav_menu'); to get a list of it.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, navigation" }
Shortcode content does not show in feed discription/excerpt I have a shortcode for my content. This shortcode organizes a couple of things in my posts on the frontend. However, when I look at my feed, the content in the entirely leaves out any content from my shortcode and only starts after the shortcode content. When I take the content outside of my shortcode it shows up in the Why is my shortcode content not showing in the description of the feed? It worked great before I introduced the shortcode! I have found a similar issue here with no resolution: < **Update:** So I just read that shortcodes are being stripped by wordpress. How can I prevent this behaviour? I have also tried this without any luck: the_excerpt and shortcodes
Ok I had to write my own custom excerpt like such: function custom_excerpt($text = '') { $raw_excerpt = $text; if ( '' == $text ) { $text = get_the_content(''); // $text = strip_shortcodes( $text ); $text = do_shortcode( $text ); $text = apply_filters('the_content', $text); $text = str_replace(']]>', ']]>', $text); $excerpt_length = apply_filters('excerpt_length', 200); $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]'); $text = wp_trim_words( $text, $excerpt_length, $excerpt_more ); } return apply_filters('wp_trim_excerpt', $text, $raw_excerpt); } remove_filter( 'get_the_excerpt', 'wp_trim_excerpt' ); add_filter('get_the_excerpt', 'custom_excerpt');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "shortcode, excerpt, feed, description" }
After deleting a post are terms, and custom meta deleted? I have a custom post type setup with a custom taxonomy. Once a post is created with custom meta data and terms in the custom taxonomy. If I delete the post does it delete the terms and custom meta?
Terms should work like categories (which basically they are but with with different names). They are attached to posts but not dependent upon them. If you delete a post the term stays, like with categories. Custom post meta is dependent upon its post and will be deleted when the post is permanently deleted. It isn't deleted when the post is 'trashed'.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "custom post types, custom taxonomy, customization" }
How to change post template I have a post featuring a product that I've created using advanced custom fields. I would like to have a link on the post that opens in a new window and displays the same product, just with a different look and info. (Note: I'm specifically looking to use a second template and not a different CSS because different info will be displayed on each template.) I've tried using the code below, but my custom template just returns a blank page. Can anyone suggest a fix? Here's the link I'm using on the original template. <a href="<?php the_permalink(); ?>?custom-template=1">Link</a> Here's the code that I'm putting at the top of the custom template. if ($_GET['custom-template'] == 1) { include custom-template.php; return; } Thanks, John
The way I see it you have two options here: 1. Pass the id to a custom template and then create a custom `wp_query` loop and use `$_GET['id']` as the id of the loop. For Example: <?php /* Template Name: Pop Up View */ //get id from your url $id=$_GET['id']; //start custom loop $query = new WP_Query( 'p=$id' ); //loop stuff and page template here ?> then you would call `<a href="custom-item-template?id=<?php the_ID();?>">Link</a>` Or going more with your current code you could do something like if ($_GET['custom-template'] == 1) { get_template_part( 'custom-template'); die(); //or exit(); } This fixed a few problems I see with your current code. One being that return can't be used outside of functions. Also uses get_template_part instead of include with is a more WordPress way to do it. Both ways should work, hopefully that gets you on the right track.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "templates" }
Advanced Custom Fields - category image I'm trying to get an image for I previously assigned to a category using ACF. here's what I'm doing: $category_image = the_field('cat_small', $linkedcat); where $linkedcat is something like category_280 When I echo $category_image, i see an array, like so: 261, , catsmall, , , Array Any idea what I'm doing wrong? Many thx! Alex
Whenever in doubt, consult the documentation and nice plugins like ACF are very well documented. It depends on how you set the image field, but from this page _Field Types -> Image_, looks like you set you field to return an object. Instead of using `the_field`, which _prints_ the value, you need **`get_field`**: $category_image = get_field('cat_small', $linkedcat); And then: $image = $category_image['url']; Or, if available: $thumb = $category_image['sizes']['thumbnail']; Also, instead of `echo`, use `var_dump` to debug arrays.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "advanced custom fields" }
How can I only show one responsive menu on mobile devices? Here's my site: < I'm running WP 3.5 and using this plugin: < It is supposed to allow you to select which menus you want to be responsive, but it doesn't seem to work. I only want the `<div id="header-bar">` menu to be displayed to mobile devices, but currently `<div id="header-nav">` is also shown. I tried messing around with CSS but I think the "Responsive Select Menu" plugin javascript is overriding it when the page loads. Any ideas?
I was missing the "theme_location" parameter for my wp_nav_menu() functions. <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, css, javascript, mobile, responsive" }
Prevent menu from loading in a page template > **Possible Duplicate:** > Remove navigation from header in custom page template Is there some way to remove `wp_nav_menu` in a page template? I can't find anything related to page templates other than redirect default theme files etc. I know that just placing the `header.php` content in the page template will do the trick but this seems a awkward hack. Thanks for any clue.
Without knowing your theme, you have at least a few options. You could 1. hide it with CSS. .your-page-template-php #your-menu { display: none; } Or 2. you could create a custom header file. For example, duplicated header.php to header-nomenu.php. And in your new file delete the menu. And then in your page template instead of calling get_header(); you'd call get_header('nomenu'); * * * **EDIT** Upon further review there _is_ a filter inside the `wp_nav_menu` function. Conditional logic will probably work as long as you haven't messed around with the query object and forgot to reset it. function wpa76334_filter_nav_menu($menu, $args){ if( is_page_template('your-template.php')) $menu = null; return $menu; } add_filter('wp_nav_menu','wpa76334_filter_nav_menu', 10, 2);
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "menus, pages, page template, filters" }
Remove navigation from header in custom page template I'm building a landing page and want to remove the navigation menu from the page. The navigation menu is in header.php which is of course in the page template. Is there a WordPress function I can use to remove the navigation menu from this specific page? I know I could do it with jQuery and do display:none for the nav menu but i'd like to do it server side before the page loads. Thanks
## Use a conditional tag: Codex References: Function Reference (is_page) Function Reference (Conditional Tags) You can specify the landing page by Page ID, Page Title or Page Slug. Here is an example: <?php if ( !is_page( 'landing-page' ) ) { wp_nav_menu( array( 'show_home' => 'Home', 'container' => 'false', 'theme_location' => 'main') ); } endif; ?> It excludes the page (in this case the page with the slug "landing-page") by placing the **`!`** in front of `is_page` No need for javascript, this should do the trick.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "menus, templates, page template" }
Filtering a Database Query In a WP_List_Table example I'm using, I am seeing how to make a general query to the `wp_options` table in the Wordpress database. For example, `$query = "SELECT * FROM $wpdb->options";` I also see that we typically create a `foreach` loop to display all the records in this table on separate rows. Sounds easy enough. But I would like to filter this query to reference an "options array" instead. This is a single value in my table. For example, I want to query a single option called `testimonial_settings` and then retrieve all the array values from this single field. I can't wrap my head around how I would do this using a `foreach` loop. Maybe a simple example showing the proper syntax would help clear things up....?
The table `wp_options` can normally be queried using get_option() So you can use something like $testimonial_settings = get_option('testimonial_settings'); to retrieve the values of `testimonial_settings`. If the stored value is serialized, it will be retrieved as an array.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, database, options" }
Role Scoper, don't allow other users to see pending posts I have noticed in Role Scoper recently (sure it wasn't always like this) that contributors can see all the pending posts of all users. Basically I have it set up so users have to submit their posts for review. But I don't really want any posts to be public in any way other then to admins and the user them self until it's been approved. Can't figure out how I'd set that in role scoper, any ideas?
Found a solutin, using the following plugin: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "user roles" }
Speed optimization of $wpdb->get_results I'm using this code to generate all my custom field values from all posts for custom field named "autor". <?php $autor = $wpdb->get_results("SELECT meta_value AS autor FROM wp_posts, wp_postmeta WHERE post_status = 'publish' AND meta_key = 'autor' GROUP BY meta_value ORDER BY meta_value") ?> <ol> <?php foreach( $autor as $autori ) : ?> <div class="autor"> <li><a href=" echo $autori->autor ?>"><?php echo $autori->autor ?></a></li> </div> <?php endforeach ?> </ol> It works okey, but the problem is that it takes a couple of seconds more (like, the page is loading for 5-10 seconds) for server to load that particular page. Is there any way to optimize this request?
Your query is incorrect in the first place because you're not doing the join correctly. What you're actually selecting with that query is just all the postmeta's autor fields, without regards to whether the post is published or not. Here's the corrected query. SELECT meta_value AS autor FROM wp_posts JOIN wp_postmeta ON (wp_postmeta.post_id = wp_posts.ID) WHERE post_status = 'publish' AND meta_key = 'autor' GROUP BY meta_value ORDER BY meta_value This will probably be faster because the proper join will eliminate a lot of the posts. It's not fully optimal, but it will give some improvement.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wpdb" }
Do i need the git directory? I have installed a wordpress site and for some reason I can see these 2 directories: .git .qidb Do I need them? Can I remove them? Will it hurt me in any way?
You should not need the .git directory **_but I would not delete it._** It contains the version control for your site, and is thus an incredibly valuable resource should you need a developer to fix or upgrade your site in the future. It also shows you a full history of the development of your site. This will save future developers time, and **_anything that saves them time, save you money!_** So leave the .git folder there, don't touch it, if you must, back it up before deleting it. If it's been put there as part of the auto installation then removing it could cause issues if your host tries to update it, or if it uses that folder to check if there's a WordPress install The .qidb folder is related to Berkeley DB, but that's unrelated to WordPress, it may be related to a previous site, but I would backup that, deleting it shouldn't impact your WordPress install.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 1, "tags": "hosting, git" }
Chance post id into post name I´d like to echo the post name instead post id. My code shows just the id. <?php global $post; $customlink = get_post_meta( $post->ID, 'clink', true ); echo $customlink; ?> Thanks Ogni
Does this meta field store some other post's ID, of which you want to retrieve the post name? If so, try this <?php global $post; $customlink = get_post_meta( $post->ID, 'clink', true ); echo get_post_field( 'post_name', $customlink ); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": -3, "tags": "post meta" }
Appending a GET-Variable to wp_nav_menu I'm creating a menu with the wp_nav_menu() function. Now I'd like to add a GET variable to the end of ever link in the menu, like this: www.mysite.com/page/?variable=123 Is there any way I can do this when using wp_nav_menu? Thanks for your suggestions
Filter `'wp_nav_menu_objects'`. You get an array as argument, a list of all items. Pseudo-code, not tested: add_filter( 'wp_nav_menu_objects', 'wpse_76401_filter' ); function wpse_76401_filter( $items ) { $out = array(); foreach ( $items as $item ) { if ( isset ( $item->url ) ) $item->url = add_query_arg( 'variable', '123', $item->url ) $out[] = $item; } return $out; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "menus" }
Edit Imported advanced Custom Fields from wordpress Dashboard I have imported advanced custom fields from one of my other site and now I want to add few more options to those fields but I can't figure out how to do it via **Dashboard**? I have imported the field using **php** export/import option of the plugin. Is there anyway that imported fields shows up in Field Groups section in Dashboard?
Fields added by PHP are not shown in the Dashboard. Recently, I came across this post in the _User Submitted Fields_ section of ACF forums: PHP Recovery Tool. The author posted a plugin in GitHub, Advanced Custom Fields Recovery Tool from PHP Export. Haven't tested, though. > Use this plugin to import fieldsets from PHP exports. **Do not use this for your workflow of importing and exporting. Use it only as a recovery tool when you lose the original database and XML files.**
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "plugins, custom field, advanced custom fields" }
Jquery on custom-field backend I need some help because I want to use some jquery (and css probably) on some custom fields on post edit screen. What I need exactly is to make , and . magically apear when user types a number: types 100, jquery makes it 1,00 and so on. The custom field I created using the plugin Types and it's named wpcf-imovel-preco. I have no clue about using jquery to manipulate elements on backend :(, that alone would be great help, so i know where to start from!
You can use the admin_enqueue_scripts hook for add custom javascript files into the backend.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, admin, jquery" }
Category location styling < Please can someone help, i have added the categories, however it appears to be off line. I have tried to style this in a class but this screws up the whole thing. I wrapped like the below but it seemed to apply to the whole of the div it was wrapped in <div class="classname"><?php get_category(); ?></div> Please can someone assist, do i edit the main style within the themes? Your help is greatly appreciated. Thanks
The way i fixed the issue was to insert the following code into my main CSS. .post-categories, .post-categories li {display:inline; padding: 0px;} I hope this helps others in this issue in the future.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories, css" }
How to determine wordpress base path when wordpress core is not loaded I have a command line script for maintaining a wordpress plugin and have to determine the wordpress base path to be able to load the wordpress core. I could just assume the script is several levels under the base path. But if I want to reuse the code and I have another similar script that needs to determine the wordpress base path I would have to adjust the level depth. This is error prone. _edit:_ `ABSPATH` can't be used since it is not defined in the command line script. In fact its value is necessary to be able to load the wordpress core and which will define it. So how do I determine the wordpress base path when the wordpress environment is not loaded yet? **Similar question:** What is the best way to get directory path for wp-config.php?
I came up with this solution. This function checks in each directory level starting from the directory of the current file for the file `wp-config.php`. If it is found the directory is to be assumed the wordpress base path. The check can of course be changed to other wordpress core files. function find_wordpress_base_path() { $dir = dirname(__FILE__); do { //it is possible to check for other files here if( file_exists($dir."/wp-config.php") ) { return $dir; } } while( $dir = realpath("$dir/..") ); return null; }
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "plugin development, command line" }
Initialize WordPress environment to use in command line script I have a command line script for maintaining a wordpress plugin and have to load the wordpress core to be able to access wordpress functions. This problem is very similar to Initialize WordPress environment to use in a real cron script. Though it differs from it as the referred question is supposed for use with a (real) cron script which can be accomplished otherwise then by starting a command line php script. As the referred question is already answered and this answer is not satisfying my needs I started this question. So what it is necessary in a command line script to initialize the wordpress environment? **Related** * Initialize WordPress environment to use in a real cron script
I came up with following solution. The script have to start with the following code. <?php if( php_sapi_name() !== 'cli' ) { die("Meant to be run from command line"); } function find_wordpress_base_path() { $dir = dirname(__FILE__); do { //it is possible to check for other files here if( file_exists($dir."/wp-config.php") ) { return $dir; } } while( $dir = realpath("$dir/..") ); return null; } define( 'BASE_PATH', find_wordpress_base_path()."/" ); define('WP_USE_THEMES', false); global $wp, $wp_query, $wp_the_query, $wp_rewrite, $wp_did_header; require(BASE_PATH . 'wp-load.php'); **Related** * How to determine wordpress base path when wordpress core is not loaded * <
stackexchange-wordpress
{ "answer_score": 35, "question_score": 31, "tags": "wp load.php, command line" }
Why is `--` converted into ndash and how can I get rid of it? I have a blog where I publish Linux tutorials. Some of the commands I listed have a `--` before command-line arguments. e.g.: `dpkg --get-selections`. The problem is that WordPress automatically switches `--` to an - (`&ndash;`). I know I could use the `&minus;&minus;` HTML entities, but the display is slightly different than the keyboard `-` sign. What I want is to disable this behaviour of WP. Is there a way to solve this?
Problem solved with this gist < . `[notexturize]--[/notexturize]` worked like a charm.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "html editor, wp kses, htmlspecialchars decode" }
Function to add custom HTML into head in custom post-type list page !enter image description here How can I add custom HTML/PHP file into head where custom post-type list showing like this ? Any Wordpress function can do this ? or I can only do by JS(jQuery) to append my custom content ?
If its okey you can hook into `admin_notices`. Like this: Change `post_type` to the real `post_type` name.. I assumed it would be "program". function wpse_76471_add_html() { global $pagenow ,$post; if( $post->post_type == 'program' && $pagenow == 'edit.php' ) { $output = '<div class="my-div">'; $output .= '<h2>'. __('My custom content (HTML/PHP)', 'program') .'</h2>'; $output .= '</div>'; echo $output; } } add_action('admin_notices','wpse_76471_add_html'); The div will be above the title... Hope its okay. Maybe there is another hook you can use: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, functions, customization, admin, editor" }
What does $_registered_pages do? I would like to know what $_registered_pages does and where am I supposed to use it. Thanks. p.s was unable to find any documentation on it online.
`$_registered_pages` is a temporary container for all registered admin menu pages. It is filled in `add_menu_page()` and `add_submenu_page()` and used used later in `user_can_access_admin_page()`. The leading underscore indicates you should **not use** it for anything. It is private and might change its name any time without warning. So do not use it in your own code, that will break one day.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "plugin development, admin" }
Setting up WordPress plugin's page I recently published a WordPress plugin but all the links of plugin page (Description, Installation, FAQs, Screenshots etc) has same two line description I used in readme.txt. Although, I properly filled up the readme.txt template. But it is not picking up anything else except description. !plugin description showing in changelog too
Interesting bug you provoked out there :) The only thing I see missing is the "short description" located between the `License URI` and the `==Description==` block. It is used in the Header area: !enter image description here While you are at it, take a look at this article: The Plugins directory and readme.txt files. And also this one about Header Images and screenshots.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "plugins, plugin development" }
Call to undefined function nocache_headers() After updating a Wordpress, or merely doing something minor like attempting to deactivate a plugin, the site might get occasionally get stuck in a non-functional state where it merely outputs an error message like the following: > Fatal error: Call to undefined function nocache_headers() in /wp-admin/admin.php What might be the cause for this happening?
There were wp files in the web root which had file size of 0 bytes. Uploading proper copies from the zip file resolved the problem. The same cause of the problem has occurred to me quite a few times in the past, but I had forgotten it.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 7, "tags": "fatal error" }
How to keep a record of changes to a custom field? I have a custom post type that hold real estate listings and I need to figure out a way to keep a record of the price of the property is listed for. For example a user lists a property for sale and then the user edits the property listing and changes the price. I need to show the price before and the new price and the date the price was changed. The price value is stored in a custom field. Doe anyone have any idea of how I can begin to tackle this issue. I basically need to keep a record of a posts custom field and the date it was changed. If i can get an idea of how to code this I can post the code here for anyone who might find this useful. Thanks
Your best option here is to create a second Custom Field and store an Array of all the versions that have been used together with the date of the update and the user who commited the changes, acually everything you need to know. Hook into the `save_post` action and compare the Value of the Custom Field with the last Value of the "HistoryArray". If it is different, push another Element into the Array and update the HistoryArray.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom field, customization, wp update post" }
File and directory permissions I installed latest WordPress 3.5 in my CentOS server. When I tried accessing ` I received a listing of the directory: ( **Index of wp-includes** ). I added the following code at the top of `.htaccess` file, and it fixed the issue: Options -Indexes IndexIgnore .htaccess */.??* *~ *# */HEADER* */README* */_vti* ## My problem When I try accessing PHP files in `wp-includes` and `wp-content` using a web-browser (for example: ` it shows a blank screen. I think it should show "Permission denied" or something like this. Am I correct? How can I achieve this? I'm concerned if my website is vulnerable to attacks. I am already aware of the Hardening WordPress article. Here are my directory and file permissions: * `wp-admin`: 755 * `wp-content`: 755 * `wp-includes`: 755 * Files have permission 644
The PHP files in the `wp-includes` directory will do nothing when accessed directly. They are designed to be `include()`'d in an existing PHP script, such as on the front-end or in the dashboard. Your `Options -Indexes` entry in the `.htaccess` file simply prevents a list of the files in a directory when no `index.php` is present. It's good practice to use this on a live server. I'm not entirely sure what the second line does; you should most likely remove it. If you're especially concerned about people attacking your server, you can prevent access to the `wp-includes` directory **completely**. To do this, create a `.htaccess` file _inside_ the `wp-includes` folder with the following content: Deny from all
stackexchange-wordpress
{ "answer_score": 5, "question_score": 5, "tags": "htaccess, security, directory, permissions" }
Adding schema itemprop image to the_post_thumbnail with filters I have tried to apply filters to the_post_thumbnail() function using apply_filters( 'post_thumbnail_html', $html, $post_id, $post_thumbnail_id, $size, $attr ); Here's the code I have come up with but doesn't seem to work completely function red_adjust_image_schema($html, $id, $caption, $title, $align, $url, $size, $alt) { $html = '<div class="image-container" itemprop="image">'. $html . '</div>'; return $html; } add_filter('post_thumbnail_html', 'red_adjust_image_schema', 20, 8); How can I add itemprop="image" to the actual image element so it registers properly? Right now it seem like I can only do a container and wrap around $html? Thanks
You've simply the wrong arguments (incl. the list of them). $caption, $title, $align, $url, $alt are too much in there. And `$attr` is missing. Not that it matters how you name the vars (as long as they start with a character), but it's easier to read for later readers. function wpse76536_image_schema( $html, $post_id, $post_thumbnail_id, $size, $attr ) { return "<div class='image-container' itemprop='image'>{$html}</div>"; } add_filter( 'post_thumbnail_html', 'wpse76536_image_schema', 10, 5 );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "post thumbnails, filters" }
WPMU - How to echo only one URL I have this code that I am using on a site to check if the current user has a blog on the our wp network and as of now it is echoing the URL for both the main site and their blog. I would like to know, how can I modify the code so that it only echoes for the user's site and not the primary/main site. <?php if(is_user_logged_in()) { global $current_user; $blogs = get_blogs_of_user( $current_user->id ); if($blogs) { foreach ( $blogs as $blog ) { echo '<li><a href=" . $blog->domain . $blog->path .'/upload-and-manage-documents/">My Documents</a></li>'; echo '<li><a href=" . $blog->domain . $blog->path .'upload-and-manage-documents/?ptype=settings&tab=gateways">Settings</a></li>'; } } } ?> <?php endif; ?> So as of now instead of 2 links, it is echoing 4. How can I fix this? Any help is appreciated. Thanks.
Ok I was able to eventually figure it out, what I did was exclude the main blog from the code. <?php if(current_user_can( 'edit_posts' )) { global $current_user; $blogs = get_blogs_of_user( $current_user->id ); if($blogs) { foreach ( $blogs as $blog ) { if($blog->userblog_id != 1) { echo '<li><a href=" . $blog->domain . $blog->path .'upload-and-manage-documents/">My Documents</a></li>'; echo '<li><a href=" . $blog->domain . $blog->path .'upload-and-manage-documents/?ptype=settings&tab=gateways">Settings</a></li>'; } } } } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "php, urls, multisite, bloginfo" }
What is the Difference in bones_comments() and comments.php I started to use Bones HTML5 Wordpress Starter Theme, but a little confuse with some built-in function in bones, There is `function bones_comments()` in functions.php but I cannot find anywhere on the files where this function is used or called. And I take a look at the code in the function it just looks like some code to output wordpress comments, and yet there is comments.php for comment_template() in wordpress. So really confuse why bones add the bones_comments() function and not use it. and what is the difference between bones_comments() and comments.php
It is a function created to be used as a hook. Inside the comments.php file is <?php wp_list_comments('type=comment&callback=bones_comments'); ?> So you can add whatever you want to the bones_comments() function and have it added to the comment output.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "functions, comments" }
Why is inline CSS added to images automatically? I have placed images on Wordpress page templates without any inline style attribute but it seem Wordpress automatically add style tag with `width` and `height` set to zero. <img src="wp-content/themes/ecoblog/images/hiw-image-1.png" style="width: 0px; height: 0px;"> Sometimes height is set to its original dimentsions and sometimes after complete refresh its values are zero. What is causing this?
Before you ask a question: maybe check on a other install of WP, is this the default? It is not? The problem is very often from plugins or themes. Disable plugins and switch to the default theme, current Twenty Twelve and check your problem. The current release 3.5 and 3.4* have not this insert as default, only the img tag with path and alt attribute.
stackexchange-wordpress
{ "answer_score": 3, "question_score": -2, "tags": "images, css" }
Custom form values without plugin I just started working on wordpress. Now i have created custom form and that form data I want to save in database and mail also. For that form creation, I have one php file which i have used as template on one page. and then that form submit, i have given action to another page [ which also made by custom template]. I am having problem, like on form submit, the action page is opening but i am not able to get data. form is like same.. <form action="/submit-idea" method="post" name="idea"> <label>Idea Outline<div class='info'>Brief description of the product or service idea</div></label> <textarea id="idea-outline" cols="10" rows="3" placeholder="" required></textarea> and on submit-idea page, I am trying to get values like, $idea_outline = $_POST['idea-outline']; But their is no values, in that variable ? and BTW, that submit-idea is php page which i have used as template on page.
This is not exactly a WordPress question, because you made an error in your form. Try adding name="idea-outline" to your textarea, and you should be fine.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "forms" }
Get the name of user who updated post Does anyone know how to get the name of the user who last updated a post/page please? (Not the post author). I can see that it is visible in the post/page revisions but don't know how to access it. Any ideas/help greatly appreciated.
You can use the_modified_author(); See < <p>This post was last modified by <?php the_modified_author(); ?></p>
stackexchange-wordpress
{ "answer_score": 7, "question_score": 5, "tags": "users" }
page 1 is not paged I have rules that only work on paginated pages (is_paged). However, they don't work on page number one (/page/1). This one is behaving exactly like the homepage (!is_paged), but unlike pages 2,3,4 etc. I want to prevent page 1 from behaving like the homepage and have it behave just like any other page. if (strpos($url,'/page/1') || is_paged()) {include 'paged.php'; } // this is to load a different template for paged results if (is_home() && !is_paged() && !$paged = 1) echo 'good'; else echo 'bad'; // this is what i want to do inside the page and cannot. It returns 'good' on both homepage and page 1 if (is_home() && !is_paged() && !strpos($url,'/page/1')) echo 'good'; else echo 'bad'; // this returns 'bad' on both if (is_home() && !is_paged()) echo 'good'; else echo 'bad'; //this returns 'bad' on both
EDIT - SOLVED: OK, so for whoever else looks for this, I found a workaround that is actually quite straightforward: on the paged.php template, set a variable such as $paged = true, than instead of !(is_paged()) use !($paged).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, pagination, homepage, conditional tags" }
How to assign custom template to specific products in Woocommerce? I figured out how to assign a template to a product category (from this thread Different template of products for specific category. WooCommerce), but I'm wondering if I can assign a custom template to specific products. EDIT: For more clarity, I want to have a certain style applied to the category page, but when I click on one of those products, I want to keep that same style.
If the changes you need are strictly CSS, you can add the category names as classes to the `body_class` via the `body_class` filter. add_filter('body_class','wpa76627_class_names'); function wpa76627_class_names( $classes ) { if( is_singular( 'product' ) ): global $post; foreach( get_the_terms( $post->ID, 'product_cat' ) as $cat ) // maybe you want to make this more unique, like: // $classes[] = 'product-category-' . $cat->slug; $classes[] = $cat->slug; endif; return $classes; } This code checks if we are viewing a single product page, then loops over all product_cats, adding the slugs as classes to the body tag. This could also be adapted for any post type or taxonomy.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "themes, plugins" }
remove admin bar new post/link/media sub menu I wish to remove the sub menus of post/link/media under the add new menu in the admin bar. I can remove the entire menu but I actually only want to remove the sub menu's $wp_admin_bar->remove_menu('my-account-with-avatar');
See the Admin Bar remove_node function: add_action( 'admin_bar_menu', 'remove_wp_nodes', 999 ); function remove_wp_nodes() { global $wp_admin_bar; $wp_admin_bar->remove_node( 'new-post' ); $wp_admin_bar->remove_node( 'new-link' ); $wp_admin_bar->remove_node( 'new-media' ); }
stackexchange-wordpress
{ "answer_score": 19, "question_score": 12, "tags": "admin bar" }
Javascript will not run properly I have this code which runs perfectly on jsFiddle. When I try to run that code on my self-hosted WordPress site, however, it will not run. (The code is exactly the same on my page, except that I added `<script type="text/javascript" src="/files/jquery-1.8.3.min.js"></script>` before the Javascript on the page.) The Javascript is directly in the Text tab of my page, JS first followed by the HTML. The form loads properly, but clicking the "Add Row" button does nothing. I had this issue on another page on my site, but it was fixed by wrapping everything in $j(document).ready(function(){ // code }); and using jQuery noConflict mode. I implemented that here (as you can see in the code), but it is not working.
As for me, in WP I always use jQuery instead noConflict mode, Try to run this code: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages, jquery, javascript" }
Which action hook can I use when a featured image has been selected I have made a plugin for wordpress which copies the image to another directory when a post has been edit. But if you only upload another featured image and don't save the post. The image has been attached to the post, but the post has not been updated. Which does not trigger my plugin function. Show which trigger (action hook) can I use to also copie the featured image? The action which I now use for the post edit is wp_insert_post(). I forgot the reason why I use wp_insert_post(), but maybe that's why it fails ;)
The `set_post_thumbnail` function uses the metadata functions to set the featured image. You have two actions to hook into that process: ### EDIT: The action hooks are now defined different Thanks @dalbaeb! * `update_postmeta`, before the data is written into the database. Previously `update_post_meta` * `updated_postmeta`, after the data is written into the database. Previously `updated_post_meta` ### SECOND EDIT: No need to panic `updated_{$meta_type}_meta` and `update_{$meta_type}_meta` still work. You will have to make a conditional, and be good to go: if ( $metakey == '_thumbnail_id' ) { /*blabla*/ }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "images, wp update post" }
How to pass NULL in where array for $wpdb->update how to get results of a row with NULL element? I have to update the row which contains only the post_id and the repeat value, 'start' and 'end' should be NULL mysql table screenshot: $wpdb->update( $schedule_table, array( 'rpt' => $event_tag ), array( 'post_id' => $post_ID, 'start' => NULL, 'end' => NULL ), array( '%s' ) ); $wpdb->print_error(); I get this error: WordPress database error: [] UPDATE `wp_MW_3_schedule` SET `rpt` = 'monday' WHERE `post_id` = 357 AND `start` = '' AND `end` = ''
My simple and quick solution is the use of a normal $wpdb->query() function: $wpdb->query( $wpdb->prepare("UPDATE $schedule_table SET rpt = %s WHERE post_id = %d AND start IS NULL AND end IS NULL", $event_tag, $post_ID ) );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "wpdb" }
Only make custom image size if uploaded via Thickbox and attached to certain page I am trying to make it so that WP will create another size image for me, but only when the image is uploaded via the Thickbox, and only when it will be attached to a certain ID. Does anybody know how to do this? The following works, but will create an image of that size for every upload, which is just inefficient. add_action('after_setup_theme', 'set_image_upload_size'); function set_image_upload_size(){ if(!{is Thickbox upload} || !{is attached to page 6838}) : // Don't know how to check this... return false; endif; /** Add an upload size for the footer images */ add_image_size('footer-logo', 60, 40, false); }
There is no solution for this as of WP 3.5. There are a couple of core tickets about introducing the ability defer the generation of specific images sizes on the fly rather than at upload time to prevent the generation of multiple images that will never be used. However, they are far from being included in core at this point. See < and <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images, thickbox" }
Retrieve current post's tags Is it possible to use get_post() to retrieve which tags were selected in the post? I would like a way to store a single post's tags into a variable.
<?php $tags = get_the_tags($post_id); ?> Here `$post_id` is the ID of the post of which you want to get tags. This is same parameter as passed to `get_post()`. When used inside the loop $post_id is optional & default to the current post.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions" }
User meta and author meta Here's what I have so far.. class emailer { function notifyHeart($post_ID) { $interests = get_user_meta( get_current_user_id(), 'interests', TRUE ); $to = the_author_meta( 'user_email', get_current_user_id() ); if(has_tag($interests[0])) { $email = $to; mail($email, "An article about Heart", 'A new post has been published about heart.'); return $post_ID; } } } add_action('publish_post', array('emailer', 'notifyHeart')); What I need to do now, before actually sending the email, I need something that checks if the user has an $interest and if so, send them an email. Any help with this?
class emailer { static function notifyHeart($post_ID) { $interests = get_user_meta(get_current_user_id(), 'interests'); $to = get_the_author_meta( 'user_email', get_current_user_id() ); $post = get_post($post_ID); foreach($interests as $interest) { if(has_tag($interest, $post)) { $email = $to; mail($email, "An article about Heart", 'A new post has been published about heart.'); break; } } } } add_action('publish_post', array('emailer', 'notifyHeart')); Here's a reworked example. It retrieves all the tags you have in database as meta, checks each of them & if it matches the one in that post's id, it will send the mail & break out of the loop.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "functions" }
Show ellipsis (...) only if the number of characters exceeds limit defined in substr I'm limiting the number of characters in the title with `substr`. But even if the title is less than 50 characters, being shown the ellipsis (...). I would not display the ellipsis if the title does not exceed the limit of 50 characters. $title = substr( $title, 0, 50 ) . "..."; > Title of my post ... (Incorrect: Title less than 50 characters in this case should not display "...") > `Title of my post that exceeds 50 characters ...` (Correct: Title longer than 50 characters are cut and accompanied by "...")
In the form you have posted this is more of PHP question - you could use `strlen()` functions to determine length of original title and apply ellipsis conditionally. However in WP context you should consider using `wp_trim_words()` since trimming based on words looks tidier and it will take care of appending string of your choice whet cutting.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "count, limit, characters" }
What is the advantage of the wp_options design pattern? As we all know, a design pattern that is used frequently in WordPress' DB code is the idea of persisting data for a particular object (blog/post/comment), indexed with a particular name or key. We see this pattern used in the following standard tables: * wp_options * wp_commentmeta * wp_postmeta As far as I can tell, the motivation for this design decision was to enable plugin/theme authors to persist data easily (e.g. by using custom fields) without having to modify the database schema. It would seem to me that there are few other advantages to this approach, since it is significantly slower and makes it harder to implement complex queries. What are the other advantages to this approach, if any? * * * UPDATE: Reading info on the drawbacks of this approach: * < * <
The ability to store abstract key-value pairs without modifying the database structure is _the_ reason. Without that, WordPress loses **_much_** of its flexibility. I can't speak for others, but the single largest reason why I develop atop WordPress is its flexible nature. To quote one of your links above, > Usually the reasoning behind doing what you are doing is because the domains need to be "user definable". If that is the case then even I am not going to push you towards creating tables on the fly... While it's true that it forces queries to be more complex, and a little slower, the benefits far outweigh the costs. But, hey, it's all about what you're doing. Don't use a hammer to bang in a screw. If you still want to use WordPress, but need to run complex queries on steady, structured sets of data, check out Pods. I hope this helps you out!
stackexchange-wordpress
{ "answer_score": 3, "question_score": 4, "tags": "custom field, database, post meta, wpdb, options" }
How can I remove the welcome message generated by the New User Approve plugin? I'm using the New User Approve plugin. After installing the plugin the top of the registration page says: > Welcome to XXX site. This site is accessible to approved users only. To be approved, you must first register. How can I erase this message? I'm am using this code: $message = apply_filters('login_message', ''); But the top says still stand there!
The second argument should be a function callback, not the actual message. You can remove the message **completely** by pasting this code into your theme's `functions.php` file: add_filter( 'new_user_approve_welcome_message', 'wpse_76823_login_message' ); function wpse_76823_welcome_message( $message ) { return ''; } Or, you can replace the message by using this code: add_filter( 'new_user_approve_welcome_message', 'wpse_76823_login_message' ); function wpse_76823_welcome_message( $message ) { return "This is my new message"; } If you need more help, post a comment below.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins" }
template_redirect not being called when using ajax Usually I hook all my custom plugins code with the `template_redirect` hook but one of the issue I encountered is it does not work for the ajax call. So if I want to target both standard calls and ajax call what hook should I use? Is `wp_loaded` a good choice?
For AJAX you need to hook into the wp_ajax_{action} hook Specifically, add_action('wp_ajax_my_action', 'my_action_callback'); add_action('wp_ajax_nopriv_my_action', 'my_action_callback'); See <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "plugins, plugin development, hooks, actions" }
Publish post facebook page & twitter automatically I need a feature in wordpress, using which a new post automatically posted to Facebook Page & Twitter. Do I need some plugin to do that.. Do you know any plugin that provides for this kind of feature? And may be support more social networks.
Download facebook auto post plugin from following link;Plugin Download URL here Follow author notes in installation and also see screenshot before installation. download twitter auto post plugin from following link plugin download link here
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "plugins, plugin recommendation, facebook, twitter, social sharing" }
How to add tags (custom taxonomy) to post class css? I am trying to figure out how to add my custom taxonomy for tags to the post class css when I already have added the custom taxonomy for categories. The code Im currently using to add the category taxonomy is - <?php $terms = get_the_terms( $post->ID, 'videoscategory' ); ?> <div class="box<?php foreach( $terms as $term ) echo ' ' . $term->slug; ?>"> This works fine but I also need to add a class for tags I've created with a custom taxonomy. I came across this code that will add the regular tags, but I need to use my custom tags. <?php $tags = get_the_tags(); if( $tags ) : ?> <?php foreach( $tags as $tag ) { ?> <span class="<?php echo $tag->slug; ?>"><a href="<?php echo get_tag_link($tag->term_id); ?>"><?php echo $tag->name; ?></a></span> <?php } ?> <?php endif; ?> Thanks.
Ok I figured out how to add the terms to div's class - In the code I have first the category, then the post type, then a custom taxonomy tag term assigned to it - <?php $terms = get_the_terms( $post->ID, 'YOUR CUSTOM TAXONOMY CAT' ); ?> <?php $post_type = get_post_type($post->ID); ?> <div class="box<?php foreach( $terms as $term ) echo ' ' . $term->slug; ?><?php echo ' '.get_post_type( $post->ID ); ?> <?php $terms = wp_get_post_terms($post->ID,'YOUR CUSTOM TAXONOMY TAGS'); foreach ($terms as $term) { echo $term->slug; } ?>">
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "posts, custom taxonomy, loop, css, tags" }
Problem with wordpress links on a live site I am trying to create a website at the following link: < The website was created with wordpress using the twentyeleven theme. The problem I am facing is as follows: As soon as you agree to the disclaimer and hit the "Proceed to .. " button, you are served with a 404 error. The page it redirects to is the "Welcome!" page which can also be accessed from the "About" section. Apart from this one page, all other pages work OK. This problem is not seen in the wordpress website on localhost. What I have done so far: 1\. Checked all permalinks. 2\. Changed the link for the "Proceed .. " button to a `?page_id` link. This does not work. 3\. Kept the permalink in the drop-down menu. This too does not work. I am at my wits end to figure out what the problem is. Any help is most welcome.
The welcome page "exists" since I can access it when I search for it, though trying to go to its link directly give me a 404 as well. As an experiment, try changing that page's slug to `welcome2`; if it works now, check if you have any custom rewrite rules set up that are overriding the welcome page. > I see that there is a `welcome.html` file present there which is a filler if your site is not yet up. Rename it to `_welcome.html`, set your page's slug back to `welcome` and try accessing your welcome page directly again afterwards (force re-load the page since you might still see the 404 come up at least once).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "permalinks" }
Different upload directory based on post type in a theme I have a lot of uploaded image files and image sizes. So it would be better to organize media files into folders based on post type. I have just read this tutorial, but as I can see it works with plugins. How to change this to use in a theme? Thanks. function custom_upload_directory( $args ) {       $id = $_REQUEST['post_id'];     $parent = get_post( $id )->post_parent;       // Check the post-type of the current post     if( "post-type" == get_post_type( $id ) || "post-type" == get_post_type( $parent ) ) {         $args['path'] = plugin_dir_path(__FILE__) . "uploads";         $args['url']  = plugin_dir_url(__FILE__) . "uploads";         $args['basedir'] = plugin_dir_path(__FILE__) . "uploads";         $args['baseurl'] = plugin_dir_url(__FILE__) . "uploads";     }     return $args; } add_filter( 'upload_dir', 'custom_upload_directory' );
If i understand your question right you want a function within your theme that adds directories for the current post_type? like: uploads/post_type_name. if so here is a function for that: function wpse_16722_type_upload_dir( $args ) { // Get the current post_id $id = ( isset( $_REQUEST['post_id'] ) ? $_REQUEST['post_id'] : '' ); if( $id ) { // Set the new path depends on current post_type $newdir = '/' . get_post_type( $id ); $args['path'] = str_replace( $args['subdir'], '', $args['path'] ); //remove default subdir $args['url'] = str_replace( $args['subdir'], '', $args['url'] ); $args['subdir'] = $newdir; $args['path'] .= $newdir; $args['url'] .= $newdir; } return $args; } add_filter( 'upload_dir', 'wpse_16722_type_upload_dir' );
stackexchange-wordpress
{ "answer_score": 14, "question_score": 6, "tags": "uploads, media settings" }
Conditional function for excluding first image from content, not working I have the following function: function remove_images( $content ) { if( ( is_category() || is_archive() || is_home() ) && has_term( 'MyCat', 'category', $postID ) ) { $postOutput = preg_replace("/\< *[img][^\>]*[.]*\>/i","",$content,1); return $postOutput; } } add_filter( 'the_content', 'remove_images', 100 ); What it is meant to do is remove the first image in the_content() on thew index page (all listing pages) only for those posts in the MyCat category. What it is doing, instead, is removing the first image from the_content() on all posts for the index page, and removing the_content() altogether on **all** of the **single pages**. Any help would be appreciated. Thank you.
> What it is doing, instead, is removing the first image from the_content() on all posts for the index page... That's because that's what your callback is telling the filter to do. It returns true for _all posts_ in your specified contexts (archive index, category index, blog posts index), _not_ just for the _first post_ in those indices. > ...and removing the_content() altogether on all of the single pages. That's because, if your conditional returns false, you don't return anything. You need to `return $content;` outside of your conditional.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, images, the content, conditional content" }
Update feed more frequently When i publish new posts, i notice the new posts do not appear in the feed ` instantaneously, there is always lag time, one or several hours. When i change something in `wp-includes/feed-rss2.php` file (just `echo 'test'`), it also takes one or 2 hour to see the `test` word in ` it means wordpress only use that file periodically. Anyone know how to solve this problem? I want whenever the ` page is open in browser, it must use `wp-includes/feed-rss2.php` file. Thanks!
Just like the pages WordPress makes normally, feeds are generated on-demand, they're not "rebuilt" or "updated" or any sort of thing like that. So posts will appear in the feed at the exact instant that they are published. If you're seeing a lag time, then you may be using a caching plugin, such as WP-Super-Cache, or some form of feed redistribution service, such as FeedBurner, which is holding a copy of the feed for some period of time and only refreshing from the actual feed periodically. In this case, you need to either configure the caching plugin to not cache the feed, or stop using the feedburner-like service.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "feed" }
How to track hits of a single media file? I have multiple media files in my WordPress Media Library. Icons, Images, PDF's and the like. I would like to have a stat counter, that gives me a statistic of the downloads/hits of those files, individually. **I already use WP SlimStat** to track page view, and I am quite happy with it. However, **I have not found a possibility to track those media files.** How can I do this?
You could use Google Analytics for WordPress. Here's an excerpt from their FAQ on how you could set it to track certain file types: > How can I track downloads? Check the box for "Track outbound clicks & downloads", after that, make sure the file types you want to track are listed in the box of extensions to track as downloads. You’ll find this input field under "Advanced".
stackexchange-wordpress
{ "answer_score": 5, "question_score": 7, "tags": "plugins, media library, statistics" }
Does dbDelta delete columns as well? I created a table using the dbDelta function and then removed a few columns and added a few. The new columns did get created but the old columns did not get deleted from the table. Is there a different way I am supposed to delete columns from the table ?
As far as I know, `dbDelta()` is primarily used to add tables to the database. It can also add or alter columns. To delete columns, you should use `$wpdb->query()`: global $wpdb; $table = $wpdb->prefix . 'table_name'; $wpdb->query( "ALTER TABLE $table DROP COLUMN column_name" );
stackexchange-wordpress
{ "answer_score": 14, "question_score": 10, "tags": "database, wpdb, dbdelta" }
Post incorrectly displaying as page I have a small WordPress install that I'm setting up, and have run into an issue that I've encountered before, but do not understand the cause. Issue: With permalinks set to `/%postname%/`, on a site with the following: 1. Home page 2. About page (slug: "about") 3. Two links to categories (there are two categories, with slugs of "digital" and "broadcast") 4. About 35 posts Most everything works as expected, however there is one post with a slug of "swampism" which displays (incorrectly) in the page.php template file, rather than the single.php template file (where all other posts properly display). How does this happen? Why does it happen? And how can I fix it and/or avoid it in the future. **Note:** Changing the permalink structure to default, or date driven is not an option. Besides, that is (in my mind) a work-around, not a solution/explanation of the problem.
I was going to make this a comment but it was getting long and I think I see an answer emerging. I'll gamble. If this is the problem URL: < you are seeing an attachment page `<link rel='canonical' href=' />` WordPress shows these when individual images are requested. I am starting with that assumption. The image on that attachement page is, interestingly, named `Swampism.jpg` which, if the pattern I see in my DB holds, means it has the slug of 'swampism'. I am betting that that is where you conflict is. WordPress is finding the image slug and loading the attachment page for it instead of finding your "page-name" slug.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "permalinks, redirect" }
Main menu navigation links and new pages Sorry i'm pretty new on wp, i would like to add new menu links and site pages, to the main top menu bar. I'm using a third parties template, and i see the top.php file which contains the top menu looks like: <div id='mainmenu-container'> <div id='mainmenu'> <?php $nav_menu_params=array( 'depth'=>0, 'theme_location'=>'main-menu', 'menu_class'=>'menus menu-primary', 'fallback_cb'=>'block_main_menu' ); wp_nav_menu($nav_menu_params); ?> </div> how does i edit this code or how can i enter anyway new links and new web site pages from backend side? thanks for help
Templates can all have unique code, and your template may or may not support Custom Menus. I would find out if you can add custom menus through your Appearance > Menus tab in the admin area. If you can't, all new pages you add from the Pages tab will most likely end up in that main menu by default. If you **can** add custom menus, then you should look up the function you are referencing here to get a good understanding of how to place your code. Also check to see if you have the option to set the menu which will be your main menu in the Menus tab.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, pages, links" }
Get featured image URL by page id I am using WordPress 3.4.1. I need to display the featured image of a page. How can I get the featured image URL by particular page ID. Any help?
Did you try anything? Its always helpful to share what you have tried. $url = wp_get_attachment_url( get_post_thumbnail_id($post_id) ); Or if you want to get the image by image size. $src = wp_get_attachment_image_src( get_post_thumbnail_id($post_id), 'thumbnail_size' ); $url = $src[0]; < < <
stackexchange-wordpress
{ "answer_score": 24, "question_score": 7, "tags": "post thumbnails" }
How to have Tiled Galleries like in WordPress.com? In a WordPress.com hosted blog, you have the posibility to create picture galleries with a different style than usual: tiles, squared tiles or circles. What plugin are they using to achieve this? I haven't found that feature in a stand-alone WordPress installation.
Tiled galleries have been proprietary feature of wordpress.com, but later also released as Jetpack feature since version 2.1 of it.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "gallery, plugin jetpack" }
Add a menu item to Wordpress 3.5 Media Manager How can add a new menu item underneath the "insert From URL" on the left sidebar in the new Wordpress 3.5 Media Manager? I've been looking at the backbone js and tried my hand at hooking into it with my own JS but without success. Edit 2: This seems to do the trick: < It should do for simple stuff, but I guess its also possible to do the same thing in Javascript. Would be nice if there was a tutorial/explanation on how the new media manager internals work.
OK, I think that I have something that is really close to be an answer: I put my code in a gist Here is the result : !custom menu screenshot I built several Backbone object to respect the MVC pattern : the `controller.Custom` is in charge of doing all the logic, the `view.Toolbar.Custom` deals with toolbar buttons, and the `view.Custom` display the inner UI.
stackexchange-wordpress
{ "answer_score": 20, "question_score": 37, "tags": "media, media library" }
Output in XHTML or HTML 5 for plugins? I'm currently writing a plugin that displays some images - possibly with captions. So, I was wondering whether to use XHTML (`<div>`s and `<span>`s) or HTML 5 (`<figure>` and `<figurecaption>`) for output. I image that the answer to this question depends somewhat on the theme being used. Is there a way to figure out which output format the user's theme is using? Or what's the best approach here? What's Wordpress doing to solve this issue?
WordPress will not help you here. In back-end use conservative XHTML 5: `<br />`, but not `<figure>` (see WP coding standards). In front-end … it is hard to determine the Doctype and the usage of polyfills, so stay with regular HTML as long as possible or load the necessary polyfills from your plugin.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "plugins, plugin development, html, html5" }
wp_redirect not working after submitting form I'm using this redirect after inserting a post. It's not working, it only refreshes the page the form is on. I know the $pid is getting the post ID so what is the problem? This is the very end of my php code for handling the form submission. $pid = wp_insert_post($new_post); update_post_meta($pid,'domain',$domain); update_post_meta($pid,'keywords',$keywords); wp_redirect( get_permalink($pid) ); exit(); Here is a pastebin of the complete code Using Better HTTP Redirects it's output is, and it links the word `here` to the correct newly published post. 302 Found The document has moved here.
You can only use `wp_redirect` _before_ content is sent to the browser. If you were to enable php debugging you'd see a "headers already sent" error due to `get_header()` on the first line. Rather than process the form in the template, you can hook an earlier action, like `wp_loaded`, and save some queries to the db if you're just going to redirect away. **EDIT** , example- add_action( 'wp_loaded', 'wpa76991_process_form' ); function wpa76991_process_form(){ if( isset( $_POST['my_form_widget'] ) ): // process form, and then wp_redirect( get_permalink( $pid ) ); exit(); endif; } Using an action, you can keep the code out of and separated from your templates. Combine this with a shortcode to output the form and wrap it all in a class to save state between processing/output, and you could do it all without touching the front end templates.
stackexchange-wordpress
{ "answer_score": 15, "question_score": 8, "tags": "wp redirect" }
Trying to display posts but getting the pages as output I am trying to display the posts on my front page of the `roots theme's base.php` file. I have added the loop as <?php while (have_posts()) : the_post(); ?> <?php echo '<h2>'; the_title(); echo '</h2>'; the_content( 'Read the full post »' ); ?> <?php endwhile;?> However, this keeps displaying just the content and title from the first page. How do i get it to display the posts? I have set the number of posts as 3 under settings -> reading .
Just save it with a suitable name like: * `home.php` * `index.php` * `archive.php` * `category.php` This link can help you: WordPress Template Hierarchy
stackexchange-wordpress
{ "answer_score": 3, "question_score": -1, "tags": "plugins, loop" }
Get number of comments per page I am trying to grab number of comments to display per page. So far unsuccessful, looking for something similar to this `$wp_query->max_num_pages;` Thanks.
From quick look at core that would probably be `get_option('comments_per_page')`. However WP functions just use this internally, why not just let them take care of it? You are not describing _why_ do you need to handle this directly.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "comments" }
Check if "Break comments into pages" is selected I am working with a `paginate_comments_links()` function and the thing is that I have customized it slightly (wrapped with a div), I need to check if check box "Break comments into pages..." in WP admin -> Settings -> Discussion Settings -> Other comment settings was checked. So the question is how would I grab the results? The issue is that if it is not checked `paginate_comments_links()` will not do anything, but my div will appear.
The check is done with `get_option('page_comments')`. But you could use another solution: $prev = get_previous_comments_link(); $next = get_next_comments_link(); if ( '' !== $prev . $next ) echo "<div>$prev $next</div>";
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "pagination" }
Return all Tags from search results I am wondering if it is possible to return a list of all the "tags" that are associated with ALL returned posts. In theory, I would then use this list of terms to build appropriate "filter by" links for refining the search. For instance: A user searches for "Foo" and there are 100 results. Would it be possible to get a collection of all the posts' tags? So, post "Foo 1" might be tagged "little bar" and post "Foo 2" might be tagged, "big bar" and "foo foo", etc and etc. I would like to do this _before_ the `while_posts()` is doing its thing. Failing that, I think I could use the `while_posts()` loop to collect all the tags for each post. This is the most obvious solution to me, except that then the list isn't where I want it in the markup. AND, I'm not sure how to include tags on page 2 (and onward) of the results.
The global `$wp_query` object is available before you call `have_posts()`. All you have to do is running through this object’s `posts` member with `get_the_terms()`. Sample function: function get_query_terms( $taxonomy = 'post_tag' ) { $list = array (); foreach ( $GLOBALS['wp_query']->posts as $id ) { if ( $terms = get_the_terms( $id, $taxonomy ) ) { foreach ( $terms as $term ) $list[ $term->term_taxonomy_id ] = $term; } } ksort( $list ); return $list; } Be aware any usage of `query_posts()` might break this list.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "search" }
Is it possible to insert images directly from the server? I've uploaded images directly to my WordPress server through FTP. I want to add these images to a post, so right now I'm using the Add from Server plugin that allows me to browse images on the server and add them to the media library. The only thing I don't like about this is that adding an image to the media library generates two smaller versions of the image that are used for thumbnails. Is it not possible to completely bypass the media library and add images directly from the server?
I think that the best option here would be to disable the generation of additional image sizes on adding an image to the media library. Doing so is fairly straight-forward: Visit the _Settings > Media_ page of your WordPress dashboard. Under the _Image Sizes_ section, change all of the values to 0. !Media Settimgs Save the changes. This will stop WordPress generating thumbnails, medium, and large sizes of every image you upload. You will also notice that when you go to insert an image, the "Size" dropdown box is missing.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "plugins, images, media library" }
Escaping a shortcode so it displays as-is > **Possible Duplicate:** > Show shortcode without executing it I've created a plugin that uses a custom shortcode to allow the user to easily split their post into columns. The problem is, when writing about how to use the shortcode in the plugin documentation on my website, WordPress interprets the shortcode and starts applying to to my content. I don't want this, rather I want the shortcode to display exactly as written. How can I do this?
The secret is called **escaping**. You need to place an extra set of square brackets around your shortcode `[[gallery]]` and it will display as `[gallery]`. Also, **double escaping** works too: `[[[gallery]]]` outputs `[[gallery]]`. There is also a Trac ticket on this topic.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode, escaping" }
Making featured image to show on home page I am working on twenty twelve theme. Whenever I post an image gallery, it shows all of images including featured image on front page same as it looks inside. I wanted it to just show featured image on home page instead of showing all. I tried but no success. Any help appreciated!! Thanks
You need to porvide more info, such as what you have tried so far. have you used `the_post_thumbnail` function? <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post thumbnails" }
How to Keep footer link remain intact? I'm a Wordpress Theme Designer. I want to have functions to make my footer links remain intact. Like some themes that use this method to protect their footer link from the theme downloaders to remove it. If they alter, change, or deltete parts or all, they will get an error! Any step by step guide or source would really appreciated! Thanks so much! Regards, Thy
If you are releasing a GPL'd theme (which WP requires, but not looking to start the whole GPL debate here) then you can't prevent someone from removing your footer link. You can ask they they don't do it. But anyone who's looking to do so will get around whatever method you employ. a side note: having these links in the footer may be more of a bad thing than good. I'd suggest reading this article on WPMU about how spammers using their themes caused them to get thrashed in their rankings.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -3, "tags": "footer" }
Contact Form 7 plugin refreshing page on submit For those with experience of the Contact Form 7 plugin - When I installed it, the form worked fine, and upon pressing the submit button, there was no page load, all done via Ajax, however now the page loads upon pressing submit. I have not made any changes to the form. I have tried deactivating then activating but the problem remains. Has anyone else had this problem before? Thanks
Have you installed any other plugins? Also check in `header.php` that there is `wp_head();` function in `<head>wp_head(); </head>` tag and `wp_footer();` before `</body>` tags ends
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "plugins, forms, plugin contact form 7, contact" }
Allow AJAX call to other roles than admin On my website, registered users (subscriber role) can send drafts and, if admins validate them, they are published. I'm trying to add a tag box to frontend editor used to send new posts. To implement the autocomplete feature I'm making an AJAX call to this URL: That works great for an administrator user, but it doesn't work for subscribers. Does anyone know any way to achieve this without calling to `admin-ajax.php`?
All the WordPress AJAX calls should be handled by the `admin-ajax.php`, wether they happen on the frontend or in the backend. To grant the access you have to register the callbackfuntion for the AJAX call add those lines to your file: add_action( 'wp_ajax_prefix_update_post', 'prefix_update_post' ); add_action( 'wp_ajax_nopriv_prefix_update_post', 'prefix_update_post' ); Be sure to add some validation in the `prefix_update_post` function, as a non loggedin user should not be allowed to send the draft. So this line should do the trick: function prefix_update_post() { if ( current_user_can( 'edit_post' ) ) { // your goodies here } } If everything works out fine, perfect, else you may have to send the userID with the AJAX call and check if the User has the correct permissions (`get_user_by('id', $userid)`)
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "ajax, tags, user roles, autocomplete" }
How can i sort the categories by ID Hi all I am newbie to wordpress I am using the wp_list_categories in the sidebar to display the categories . How can i display thus categories sort by id any one much appreciated... <?php wp_list_categories('exclude=73');?>
`wp_list_categories` takes an `orderby` parameter which accepts : * ID - Default * name * slug * count * term_group So the default behavior of wp-list-categories is to order by ID but you can specify that like so: <?php wp_list_categories(array('exclude'=> 73,'orderby' => 'ID'));?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "posts, categories" }
Pagination Adding Numbers in Strange Fashion Below is my pagination code. It can be seen in action at this link. When I start on page one it displays the first 3 pages and page 9 (the last page). When I go to the second it displays the first 4 and page 9. I find this to be odd behavior and expect the numbers to be added in a traditional behavior, like that code found on CSS tricks. Does anybody know what I've done incorrectly in my code below? // the block for pagination global $wp_query; $big = 999999999; // need an unlikely integer echo paginate_links( array( 'base' => str_replace( $big, '%#%', get_pagenum_link( $big ) ), 'format' => '?paged=%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => $wp_query->max_num_pages ) );
What you are seeing, I believe, is a result of `paginate_links` using three blocks of numbering-- first, middle, and last. If you had enough pages you'd get, for example, when browsing page 50 ... > _1 2 3 ... 49 **50** 51 ... 98 99 100_ If you imagine the "middle" numbers overlapping the "first" numbers you'd get 3 or 4 or five numbers bunched up. You can play with the `end_size` and `mid_size` parameters and try to get something you like better, or use `'type' => 'array'` and write your own display function to convert the resulting array into actual pagination links.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "pagination" }
custom changes removed after plugin update Ok that's something normal, files are being downloaded again and the code changes. What should I do if I don't want some changes to take place? For example a gallery plugin I use recently updated and a border I didn't want to appear in the gallery now exists again. Updates should always take place for security reasons but how should I override such behavior? Is there a way I can have another file that doesn't allow for example that border effect to take place ? Maybe with jQuery somehow ?
If it's just a CSS change, load your own CSS stylesheet to override their CSS. If it's the HTML of the plugin, then you will need to look at filter hooks to see what you can change. Some plugins are developer friendly and supply some filter hooks allowing you to change various things the plugin does; for others, you will need to get creative.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, jquery, css, updates" }
How can I install WordPress as blog provider , stable? can I make a Blog Provider like Wordpress.com? Which features and Plugin exist in wordperss.com but we cant have them in our clone site of WordPress free source?
Install WordPress as a multisite installation. Check Codex! for how to start. You can google for more tutorials on how to setup a multisite installation.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, hosting" }
Programmatically publish a post (custom post type) with custom fields I have a custom post type 'Participant' with many custom fields. I also have a form with corresponding input fields for the user to fill out. When he submits the form, I want a new post to be generated with each custom fields containing the value chosen by the user. Is it possible to do and if so, how?
Use wp_insert_post() and add_post_meta(), like this: // insert the post and set the category $post_id = wp_insert_post(array ( 'post_type' => 'your_post_type', 'post_title' => $your_title, 'post_content' => $your_content, 'post_status' => 'publish', 'comment_status' => 'closed', // if you prefer 'ping_status' => 'closed', // if you prefer )); if ($post_id) { // insert post meta add_post_meta($post_id, '_your_custom_1', $custom1); add_post_meta($post_id, '_your_custom_2', $custom2); add_post_meta($post_id, '_your_custom_3', $custom3); }
stackexchange-wordpress
{ "answer_score": 41, "question_score": 21, "tags": "custom post types" }