INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
how to create extra post thumbnail with merge of an icon image? I am searching a way to merge image of play button icon to featured image of the post. Bay be possible between add_image_size process. if ( function_exists( 'add_image_size' ) ) { add_image_size( 'post-play-icon', 90, 62, true ); //(cropped) }
Personally, I wouldn't take this route. Instead I would apply a PNG client-side, using CSS. This has the advantage of allowing you to swap out your play icon as you see fit.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post thumbnails" }
Conditional check to see if a bootstrap.css is included in a theme I am creating a shortcode plugin for Bootstrap framework that will go along with my theme. However since this would be released to the plugin, if a users's theme already has Bootstrap.css included, is there a way for me to check this from a plugin?
You _might_ be able to use `wp_style_is()` to do this: $style = 'bootstrap'; if( ( ! wp_style_is( $style, 'queue' ) ) && ( ! wp_style_is( $style, 'done' ) ) ) { //queue up your bootstrap wp_enqueue_style( $style, $path_to_bootstrap, $deps, $ver, $media ); } This comes with all the same caveats as @Milo's solution -- it'll only work _if_ the copy of bootstrap.css was registered or enqueued with a handle of `bootstrap`. ### References * `wp_style_is()` * `wp_enqueue_style()`
stackexchange-wordpress
{ "answer_score": 8, "question_score": 3, "tags": "plugin development" }
Featured Image inserted through custom query, does not show up I need to transfer all my records from OpenCart to WooCommerce powered WordPress site. I used custom query to insert the image urls from opencart db to wp_posts as attachment and guid as the URL of the image, along with post_parent being the product id for that particular image. While the listings show in Media, it still does not load show images and also does not appear on Featured Image box of related products. But if I copy the url from Media manager and open it in new tab. The image shows up just fine. What could be the reason? Also is there any other way to transfer OpenCart data to WooCommerce? Any help would be appreciated. Regards
I am sorry for the incomplete question. Also I managed to solve it. It was missing "_wp_attachment_metadata" post meta.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post thumbnails, migration" }
Show recent posts in a table format In the index.php template I want to display posts in 3columns in a table format. How can I do this? I don't want a list format cause I have variable hight image sizes
You still can use lists - just use proper CSS (every third li - first li in every row - should have `clear` property set; You can use CSS classes or :nth-child selector to do this). If you really have to use table (I don't suggest it - it's not a very good idea, because it's not semantic), you can do something like this: <table> <?php while ( have_post() ): the_post(); ?> <php if ( $wp_query->current_post % 3 == 0 ): ?> <?php if ( $wp_query->current_post ): ?> </tr> <?php endif; ?> <tr> <?php endif; ?> <td> ... YOUR POST GOES HERE </td> <?php endwhile; ?> <?php $i = $wp_query->current_post; while ( $i % 3 != 0 ): $i++ ?><td></td><?php endwhile; ?> </tr> </table> Not tested it, so it can be a little bit buggy, but idea should be clear.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, table" }
Accept code input into Options Framework I'm using Options Framework for a theme. I'd like to add a theme option to add Google Analytics code to the front end's `<head>` section. What is the options.php code to create an input box which won't strip `<script>` from the input?
A better approach would be to have the user simply enter their tracking script ID. You know, something like `UA-XXXXXXX-XX`? Then in your `header.php`, output the standard tracking script: <?php if ( $ga = get_option( 'google_analytics' ) ) : ?> <script> var _gaq = _gaq || []; _gaq.push(['_setAccount', '<?php echo esc_js( $ga ) ?>']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? ' : ' + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <?php endif ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "options" }
How can I make front page to display custom taxonomy page? If I have this URL for my custom taxonomy term ` how can I show it as the main page ` like it is available to do for the static pages at `Setings` > `Reading` menu? `.htaccess` solutions are acceptable, changing theme's `index.php` is not. Update: # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] RewriteCond %{REQUEST_URI} ^/work_type/vehicle-transporting/ RewriteRule ^(.*)$ / [P] </IfModule> # END WordPress Why it didn't help?
I agree with @KrzysiekDróżdż While you should probably be able to do this it might be unnecessary work. However, this works with I test it, just change the category/term name and the template name (the part in `get_template_part`), and maybe the `is_main_query() && $qry->is_home()` conditional if you need to: function pregp_home_cat_wpse_104619($qry) { if (is_main_query() && $qry->is_home()) { $qry->set('category_name','aciform'); $qry->set('ignore_sticky_posts',true); add_action('template_redirect','tr_home_cat_wpse_104619'); } } add_action('pre_get_posts','pregp_home_cat_wpse_104619'); function tr_home_cat_wpse_104619() { get_template_part('category','aciform'); exit; } I have never tried to do this in production, so "when I test it" means that I've spent about 10 minutes and don't see any obvious problems. I make no promises. Barely tested. Possibly buggy. _Caveat emptor_. No refunds.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom taxonomy, templates" }
How to move a WordPress multisite? I have a WP multisite installation like this: 1. www.mysite.com 2. www.mysite.com/anothersite Now, I'd like to move www.mysite.com/anothersite to be www.mysite.com. Is it possible?
You should be able to export `www.mysite.com/anothersite` to a WXR file using **Tools » Export** in your WordPress backend -- `www.mysite.com/anothersite/wp-admin`. Then you can go to `www.mysite.com/wp-admin`, remove the existing content (delete your existing posts / pages / etc -- export them first if you want/need a backup) and then use **Tools » Import** to import the WXR file.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "multisite" }
remove a single post_meta I created a plugin that has multiple meta boxes. One meta box saves a single record by using `update_post_meta()`. Another meta box saves multiple record by using `add_post_meta()`. I do not have revisions turned on in the post_type. How would you `delete_post_meta()` a single specific record in the meta box that uses `add_post_meta()`? Best practice advise is needed. If you're going to send the whole `$post->ID` and it will get the array of records, how can I detect the specific `meta_key` set to be deleted? Here is the code on github: <
I'd say there is barely enough information in the question to speculate on an answer but it sounds like to me that... If your data is saved in individual key/value pairs then `delete_post_meta` will do it. You would pass the function a post ID and a key name: `delete_post_meta(1,'keyname');`. It will delete the whole key/value pair. If you have multiple bits of information saved as a serialized array/object then `delete_post_meta` **_will not work_**. You will need to pull the data for the key you want with `get_post_meta`, alter the array/object in `PHP` to remove the key/value you want to delete, and then save the altered data with `update_post_meta`. < <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "metabox, post meta, customization" }
Get background color for Live Preview with Theme Customization API? This could very well be a stupid question, but I'm working on a WordPress theme (check the link to see what I'm talking about, then read on)... You'll see the Post Formats icons are surrounded by a white circle, which has a border color matching the custom background color. I know that Live Preview includes background color by default, but I'm wondering how to change this border color with the background color, as they need to match. Really, I just need to know what setting I need to use with `postMessage`, or if such a mechanism is possible at all. Thanks for any and all help! I know it's a quite unique situation, since I can't find anything remotely close to the topic here, on Codex, or Google, or anywhere.
If you're using the built in custom background stuff, it's already all using postMessage. So, just bind a function to the `background_color` message and adjust your border color accordingly. Something like this, I expect: wp.customize('background_color',function( value ) { value.bind(function(to) { jQuery('whatever').css('color', to ? to : '' ); }); }); Obviously, change the jQuery call in the middle to adjust whatever you're trying to adjust. Some of the basics I didn't cover, such as hooking that JS into the previewer and such, are here: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, theme customizer, custom background" }
creating a second image attachment template? Hi i am trying to create a second image attachment template. I have one, but I have created another. In the second one I want the attachments that are under a certain category of a post to have a different view from the rest. Here is what i have in the nomrmal photo attachment page to try to call the category <?php $post = $wp_query->post; if ( in_category('4679') ) { include(TEMPLATEPATH . '/bet-photo.php'); ?> but the problem is, It's still showing the old attachment page and not the new one. What am i doing wrong.
`attachment.php` is not the only template file for attachment display. mime-type based template files get priority. > * MIME_type.php - it can be any MIME type (image.php, video.php, application.php). For text/plain, in order: > 1. text.php > 2. plain.php > 3. text_plain.php > > > < I expect that that is the issue you are seeing. Check your theme for `image.php`. There is a further problem with your code. Attachments don't have categories as far as I know. The category is inherited from the parent post. That means that you will need to pass the parent post ID to `in_category`. if ( in_category('2', $post->post_parent) ) { get_template_part('bet-photo'); } I would also suggest `get_template_part`, as in my version of the code, instead of PHP's `include`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, templates" }
How to get new post URL? I'm wondering... how can I get the new post URL in my theme? Is there a built-in function for this? So, it should return something like < Connor.
admin_url('post-new.php'); The `admin_url` function will handle generating most of the link, you just need to give it the final component. You can pass in `GET` parameters as well. Just look at the backend URL to see what you need. admin_url('post-new.php?post_type=page'); Or using `add_query_arg` as suggested by @Rarst ... add_query_arg(array('post_type'=>'page'),admin_url('post-new.php')); It is overkill for simple URLs but useful for dynamic ones.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 1, "tags": "posts, functions, themes, wp admin" }
Media Library page super slow, loading up full quality images On my WP site (which sells retail products), I have large images (up to 4000x4000 px) so people can zoom in. Unfortunately, when adding images to a page and using the Media Library, the images all load up at full quality (though resized down). This makes the Media Library page load up really slowly, and make my browser slow to a crawl. Why is it doing this? Why isn't the ML page using thumbnails? If I click on "Media" on the left admin menu, that list of images are proper thumbnails, but when adding media to a page, the list that comes up is using full quality images. Is this a bug in WP?
Found the issue. It's with the theme itself, not WP. An update to the theme has fixed it.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 1, "tags": "media library" }
Get meta field value of all catgories I'm setting a meta field for the category and getting the meta value of each field like this: $cat_meta = get_option( "meta_field_$cat1" ); if (isset($cat_meta['color'])){ $cat1_color = $cat_meta['color']; } Can I get the non empty meta field value of all categories using a loop?
If you'd use the get_categories() function to get all the categories, you can then loop through them. Partial pseudo code, but this will do the trick: $categories = get_categories( array() ); $colors = array(); foreach ( $categories as $category ) { $cat_meta = get_option( 'meta_field_' . $category->slug ); if (isset($cat_meta['color'])){ $colors[ $category->term_id ] = $cat_meta['color']; } } PS. I don't know if the field in the options table is using the slug or the category id. The colors array will be filled with id's of the category as key and value of the meta field as value. PPS. `get_categories()` function call might need some extra parameters in the array, adjust to your liking using the available parameters. PPPS. While my answer technically answers this question, this answer by s_ha_dum is actually a better approach (might require some more refactoring though).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, themes, metabox" }
How to check if post has any tag? I am displaying post tags like this: <div class="tags"><?php the_tags('<span>Tags</span>' , ' '); ?> </div> It works fine, but if the post does not have any tag, then it adds empty div <div class="tags"></div> So, how can I use the condition to check if post has any tag, then display above.
Make better use of the parameters: <?php the_tags( '<div class="tags"><span>Tags</span>', // before ' ', // separator '</div>' // after ); ?> Now you will never get any useless markup, because WordPress will not print anything when there are no tags for the current post.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "theme development, themes, tags, conditional tags" }
count number of user comments with a specific comment meta value I am using the code below to count the number of comments by a certain user: global $wpdb; $count = $wpdb->get_var( 'SELECT COUNT( comment_id ) FROM '. $wpdb->comments .' WHERE user_id = '.$user->ID.' AND comment_approved = "1" AND comment_type NOT IN ("pingback", "trackback" )' ); I am in addition, using a comment meta field ('consider') which takes 0 or 1 as values. To get its value I use: get_comment_meta($comment_id, 'consider',true); How can I merge these two operations so that I get the number of comments submitted by the user and which have the meta value `'consider'` equal to `1`? I am not an SQL user and it seems that I need to use inside my SQL query the table `wp_commentmeta`? Your help is always appreciated.
Your basic question is a pure SQL question. $count = $wpdb->get_var( 'SELECT COUNT( comments.comment_ID ) FROM '. $wpdb->comments .' as comments LEFT JOIN '.$wpdb->commentmeta.' AS cmeta ON comments.comment_ID = cmeta.comment_id WHERE user_id = 1 AND comment_approved = "1" AND comment_type NOT IN ("pingback", "trackback" ) AND cmeta.meta_key = "rating" AND cmeta.meta_value = 5' ); I cleaned that up a bit to be more readable. What you are doing with that SQL is pretty close, possibly identical to, what you'd get with .... $args = array( 'type' => '', 'user_id' => '1', 'count' => true, 'meta_key' => 'rating', 'meta_value' => '5', ); $count = get_comments($args); You aren't explicitly excluding trackbacks and pingbacks with that but I am pretty sure that trackbacks and pingbacks will never have an associated user ID, so you are excluding them by that mechanism.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, comments, sql, comment meta" }
Automatically create a default set of posts for each new registered user Is there a plugin, or a way to automatically create a set of default posts for a new user when they register? I suspect that the answer might be to hook into the existing wordpress events - can anybody suggest a way to get started?
A combination of `user_register` and `wp_insert_post` should work fine: add_action('user_register', 'create_postset'); function create_postset($user_id) { // userinfo $user_info = get_userdata($user_id); // Create post objects $post_1 = array( 'post_title' => '1st post created for ' . $user_info->user_login, 'post_content' => 'Lorem Ipsum', 'post_status' => 'publish', 'post_author' => $user_id ); $post_2 = array( 'post_title' => '2nd post created for ' . $user_info->user_login, 'post_content' => 'Lorem Ipsum', 'post_status' => 'publish', 'post_author' => $user_id ); // Insert posts into the database wp_insert_post($post_1); wp_insert_post($post_2); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, users" }
get comment data using comment id I am using the `get_comments()` function which works well if I give it any array of parameters except if I give the following array: $defaults = array('ID' => $comment_id); $com=get_comments($defaults ); The resulting array contains all data for all comments of my website. I want to get only the data of the comment with id = $comment_id. Thank you for your feedbacks.
I am sorry for wasting your time I think there is a simple function that can do this: <?php $defaults = $comment_id; $com= get_comment($defaults ); ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, comments" }
Custom field within shortcode I'm currently using the 'WP Simple Paypal Shopping Cart' plugin to get up a simple paypal e-commerce site, it's super easy to use, but to save the client having to write shortcode, I've set up custom fields in the back-end to input the product name and price. The `Add to Cart` button is generated using a simple piece of shortcode like so: <?php echo print_wp_cart_button_for_product('Product Name', Product Price); ?> Obviously replacing `Product Name` and `Product Price` with the name and price you're adding to the site. I have 2 custom fields set up like so: <?php the_field('product_name' ); ?> <?php the_field('product_price' ); ?> I'm trying to figure out if there's anyway to put those custom fields inside the shortcode, replacing `Product Name` and `Product Price` and thus allowing people to add products to the site without having to write any shortcode. Any suggestions would be greatly appreciated!
If you want to put the custom fields inside the shortcode...you actually should put the custom fields inside the shortcode. Be sure that your fields content does not get echoed, according to ACFs resources you have to use `get_field($field_name)` within the loop. Try: <?php echo print_wp_cart_button_for_product(get_field('product_name'), get_field('product_price')); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, shortcode, advanced custom fields, paypal" }
WP Customizer - what types of fields is it capable of supporting? I just found this reference of WP Customizer types of data input: < But I wonder if there's an option to have for instance a range slider? Something that would allow users to pick a value between `50px` and `200px` or between `1em` and `2em`? Ideally it should also allow switching units - like from `px` to `%` and vice versa. Is this possible at all or does it require some custom extension? I also noticed that textarea isn't there.
The reference you pointed at just lists the **built-in** data input types. You can always add you own by creating a custom Customizer control. Follow Otto's guide to create a textarea control. If you know your HTML, it should not be harder to implement a range slider. I personally use the Customizer API to modify the `background-position` CSS property of the background image using the mouse dragging movement (see the git repo). Possibilities are endless !
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization" }
how to get the top 10 popular blogs Our wordpress sites have `many many users`, each of them have an blog account, they can write posts,comments and so on. Now I want to find out `the top 10 popular blogs`, according to or order by `comments`, or `blog visite number`, or manybe `some other stands`. Yes, I can find out the most 10 comments of the posts, but can I get the blogs? A litter difficult. Anyone could you please show me some ideas, thanks in advanced.
If I understand you correctly, something like this should help you. global $wpdb; $results = $wpdb->get_results( "SELECT post_author, SUM(comment_count) as comments FROM {$wpdb->posts} WHERE post_type='post' AND post_status='publish' GROUP BY post_author ORDER BY comments DESC LIMIT 10"); This will return you 10 authors of most commented posts (with highest sum of comments count of each post they have written). I'm not sure if this is what you wanted though.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, comments, query posts, users" }
How do i display the built-in gallery inside a widget? I want to display a specific gallery (without a plugin = WordPress built-in gallery) inside a widget. I tried the shortcode `[gallery ids="717"]` but that doesn't work. Maybe a workaround could be enabling shortcodes inside widgets? if yes, how do I do that?
Widgets don't usually allow shortcodes in them (they treat them as normal text). What you have to do, is to tell this widget, it should run `do_shortcode` on it's text. To do it, you can use this snippet: add_filter('widget_text', 'do_shortcode'); Just place it in your `function.php` file. Then you can place shortcodes in Text Widget and they will work normally.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "widgets, shortcode, gallery" }
SQL: Select wordpress posts with given text string and add a custom field to them? I want to select all wordpress posts that have a certain text string. Then to add a custom field to all those posts. Here is what I figured out so far but it doesn't work INSERT INTO wp_postmeta (post_id, meta_key, meta_value) SELECT ID AS post_id, 'customer_reviews' AS meta_key, 'On_or_delete' AS meta_value FROM wp_posts WHERE ID IS IN (SELECT post_id FROM wp_posts WHERE post_content LIKE '%Customer Reviews%') AND post_type = 'post'; Anyone know how to do this please?
Here you go (you're really close): INSERT INTO wp_postmeta (post_id, meta_key, meta_value) SELECT ID AS post_id, 'customer_reviews' AS meta_key, 'On_or_delete' AS meta_value FROM wp_posts WHERE wp_posts.post_content LIKE '%Customer Reviews%' AND wp_posts.post_type = 'post'; ` Edit: You could also just change IS IN to IN. I rewrote the from part of the query since a subquery was unnecessary though.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, sql, phpmyadmin" }
Conditional tag in Widget Logic for checking if top level page or if subpage I'm using the Widget Logic plugin to show widgets on certain pages using Wordpress Conditional Tags (or any general PHP code). What I would like to do is only show a widget on child pages, not top level pages. I tried both of the following but they both return true on all pages (so the widget shows on all pages): global $post; return ($post->post_parent != 0); and global $post; return ( is_page() && $post->post_parent ); Note I tried this for testing and the widget displays on page ID 61 and its children, not just on its children as I was expecting: global $post; return ($post->post_parent=="61"); Any tips? Thanks!
Apologies, turns out it was a problem with my theme - using `get_posts` to list child pages outside the loop without `wp_reset_postdata`. So a `global $post;` conflict I guess. `global $post; return ($post->post_parent != 0);` works fine.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, widgets, conditional tags" }
Post 2 Post: Getting connected 'person' from post author I am using the amazing P2P plugin (many thanks Scribu!) and I am having an issue that is probably right in front of my face but I just can't see. I have a 'People' as CPT and I have connected that to 'Users' with a 'Person_to_User' connection I created. On single posts I want to get the connected 'person' in my 'People' CPT from that post author. It seems like that should be fairly simple to do but my brain is hurting from trying to get this and I can't spend much more time on this.
On single post, try something like this: $author_id = get_the_author_meta('ID'); $people = get_posts( array( 'connected_type' => 'people_to_user', // replace with whatever 'connected_items' => $author_id, 'suppress_filters' => false, 'nopaging' => true ) ); Now `$people[0]` references the first (and only) author related to the post you're on. So `$people[0]->ID` can be used to get the various bits of content, thumbnail, custom meta, etc.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, plugin posts to posts" }
Create Post tabs in single-{content-type}.php with Custom Field values My requirement is exactly similar to Tabbed Post. I have Advanced Custom Fields (ACF) plugin to store data. So pulling up the requirement from the wordpress support thread: > Movie Summary | Synopsis | Screens | Trailer | Comments | Add your Review Movie summary is the_content(), Synopsis is the_excerpt(), Screens and Trailers are custom field values. I want to know how I can split the content i.e. Summary, Synopsis, Screens, Trailers into Tabs which will reload the page. I do not want to change the tabs using javascript and specifically want to reload page every time. A working example would be: Example Thanks in advance.
You can use rewrite endpoints to achieve this. First, register your endpoints: function wpa_movie_endpoints() { add_rewrite_endpoint( 'synopsis', EP_PERMALINK ); add_rewrite_endpoint( 'screens', EP_PERMALINK ); add_rewrite_endpoint( 'trailer', EP_PERMALINK ); } add_action( 'init', 'wpa_movie_endpoints' ); So now in addition to ` (or whatever your particular permalink structure is), you'll have: You can then check for the existence of these query vars in a template action, or in the template itself, and show the appropriate content: global $wp_query; // may be necessary, depending on where you're using this if( array_key_exists( 'synopsis', $wp_query->query_vars ) ){ echo 'show synopsis!'; }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "custom post types, posts, tabs" }
Do not show on homepage functions.php code needed I'm using a plugin called Float Left Right Advertising however I don't want to work on the homepage. I tried adding this code into the functions.php but it doesn't work: add_action( 'float_left_right_advertising' ); function float_left_right_advertising() { if ( is_home() ) { wp_deregister_script( 'float-left-right-advertising' ); } Can someone please help me with this?
I don't think your code should work. You have to `add_action` to some hook (this function takes at least 2 params and you only use one of them). add_action( $tag, $function_to_add, $priority, $accepted_args ); Also there is no script called `float-left-right-advertising` registered by this plugin. Something like this, on the other hand, will work: function disable_flradv() { if ( is_home() || is_front_page() ) { remove_action('wp_footer', 'append_code_to_body'); } } add_action('wp', 'disable_flradv'); PS. You also have to be careful, if you want to use `is_home` (and so on) functions. You shouldn't use them before `wp_query` object is initialized.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions" }
How to update theme from localhost to online site I am currently working on a project, actually we have an online site, we are thinking of revamping this. On this online site we have many blogs already. We have purchased a theme also and doing many customization on `localhost`. How is this possible to update the theme with customization and pages on `online server` from `localhost` without affecting the blog posts?
This depends on your set up. You essentially have two things to move, the Files (images, css, js, php) and the Database. Moving the theme files is easier, I tend to zip all the theme files on `localhost` (wp-content > themes > your theme) then install it on the live site under themes > upload which lets you add the zip. EDIT: You can also use ftp to move the files but it seems to be slower and not as clean. Now moving the database which controls the pages and menus things get a bit more tricky. It depends on a few things, * **If you don't have any data on the live site** (or want to start fresh) you can simply move the database but **you will lose all other data on the site** * **If you have data on the live site** you can use the export then import to move post and pages however this will not move the menus. * I typically recreate the pages/menus on the live site then add the theme. Hope this helps.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "customization, updates" }
NextGen Plugin: on finding images tags I'm trying to understand (and find) where nextgen save images tags. I tried in ngg_picture table without any result ... Do u know where they are? Are they some kind of standard wordpress tags?
NextGen uploads your images basically as Attachment Post types. This means that the tags themselves are stored in the `wp_terms` table
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin nextgen gallery" }
Can't upload files I've been developing a wordpress website (with a custom theme) for a month. Today I wanted to upload an image to a page and I got a message saying there was an error and I should try again later. I tried to upload the image directly to the library and I got the following error: > 1096 Notice: ob_end_flush(): failed to delete buffer zlib output compression. in (...)/wp-includes/functions.php on line 2707 I deactivated all plugins, that didn't work. I tried changing the theme to twenty twelve, that didn't work. Is there anything I can do to fix this issue, or at least understand what this is all about?
Apparently this is a new Wordpress bug (I'm using version 3.5.2). Just set wp_debug to false and it works perfectly again. Hopefully they'll fix this soon. define('WP_DEBUG', false);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, uploads, media" }
How to redirect non-logged in users to login with post_password_required() I have created a membership site which is working how I would like in that non-members cannot view private pages. However, I want that when someone who has not logged in, clicks on a link that links to a private page, they should be directed to my login page. The closest I can figure out is using post_password_required(), but it doesn't seem to be working. I don't want to hide the links from non-members. function redirect_to_login() { if( post_password_required( get_the_ID() ) ) { wp_redirect( "index.php?p=50" ); } } add_action('wp', 'redirect_to_login');
The function you are using-- `post_password_required`\-- is true for **_password protected pages_** , not for **_private_** pages. I am honestly not sure which you mean, but if you do mean "private" as in most of your description then... I am not aware of an `is_private` function but you can check the post object itself. There is a catch though. "Private" posts are rabidly protected. A user without permissions to see the post will get a 404. I think the following will work, but due to the nature of "private" posts this may still be buggy. It has not been rigidly tested. function redirect_to_login() { global $wp_query,$wpdb; if (is_404()) { $private = $wpdb->get_row($wp_query->request); if( 'private' == $private->post_status ) { wp_safe_redirect(home_url(get_permalink(188))); die; } } } add_action('template_redirect', 'redirect_to_login');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "filters, login, wp redirect" }
User accounts for saving form data? I have a handful of forms on my WordPress site that people fill out, sometimes repeatedly. They can be fairly long, time-consuming forms, so I'm hoping to find a solution where a user's form data can be saved to the forms that they fill out so that they don't have to go through it all again the next time they return to the site. Does anyone have any experience with something like this?
I would do it like so: 1. Allow them to register on your site. 2. Save their forms as WordPress user meta (use `update_user_meta`). 3. Modify your forms (so they _prefill_ themselves with these saved informations). (use `get_user_meta`)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, forms, user registration" }
Have lots of meta for posts, is it better to get at all at once or each individually I have a directory website and am doing a bit of a redesign/restructure. I have quite a few meta fields for each entry, i.e. address, city, country, website, where to buy their products, social links, background and so on. I don't display all the meta data in the same place in my layout. So my question: Is it more efficient to use `get_post_meta($id,$key,false)` and have all my meta values stored in a `$variable`, or is it better to get each individually? I would assume it is the former, but wanted to get some feedback.
Assuming you're retrieving the posts using a standard WP_Query in some manner, then the postmeta data is automatically retrieved for all the relevant posts and cached in memory. When you later call `get_post_meta`, the data is simply returned from here. So honestly, it doesn't make any significant difference which approach you take. The `get_post_meta` function isn't making database calls unless the data isn't in memory already. If you're making a WP_Query and have no need to cache the postmeta info, you can set the `update_post_meta_cache` argument in the query to false. Similarly, you can set the `update_post_term_cache` to false to prevent it from caching relevant terms from the taxonomy system as well. These can speed up a query for specific cases where you know that you don't need the meta/terms in advance.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post meta" }
comments_template not working correcly in custom template files In a template file that I am using as page, I want to allow only 2 users to post comments and allow to all other users to only see these comments( not allow them add comments). my template file is: <?php get_header(); ?> <?php if (get_current_user_id()==1 or get_current_user_id()==2 ) { comments_template( '', true ); } else { comments_template( '/comments-with-no-form.php', true ); } ?> <?php get_footer(); ?> Normally, when I remove `comments_template` from single.php, or just remove the `<?php comment_form(); ?>` from comments.php, changes apply. But in separate template file, nothing is working. The file `comments-with-no-form.php` is never executed (only style of comments.php changes). Your help is appreciated.
This if statement is really wrong : if (get_current_user_id()==1 or get_current_user_id()==2 should be : $user_id = get_current_user_id(); if ($user_id==1 || $user_id==2 )
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "comments, templates, comments template" }
How to run multiple websites from single WordPress setup I want to create a website like visahq.com in WordPress, actually visahq.com has multiple websites like visahq.in for India, visahq.ru(will be shown in Russian) for Russia etc. and each TLD has multiple sub-domains like visahq.in has a sub-domain for Australia < like on for each country. Content of all websites are almost same with some changes based on conditions. My problem is I want to manage all TLD and sub-domains on a single WordPress setup how can I do this with WordPress.
You could set up a multisite installation with sunrise configuration. This would allow you to manage one installation for your multiple domains. Be sure your hosting is ready for it.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "php, htaccess" }
Post thumbnail dependant on category I have two categories (our work and news) and only one single.php If looking at a single post in the news category then I want to show the thumbnail too so have inserted: `<?php if ( has_post_thumbnail() ) {the_post_thumbnail('medium');} ?>` But I dont want this to appear if viewing a single post within the our work category, what can I add to remove this for category ID#2?
You could do this : $categories = get_the_category($post->ID); $cat = $categories[0]->cat_name; if ( has_post_thumbnail() && $cat == 'news' ) { the_post_thumbnail('medium'); } * _EDIT: the code grabs the post category, line 2 grabs cat name from the object and I use it as a condition in if statement *_
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, images" }
Get a list of all registered actions I'm trying to debug a plugin which I didn't develop and I want to list all the registered actions. I've read this SO thread: * WordPress: How do I get all the registered functions for 'the_content' filter \- StackOverflow But it's specific to one hook and it's about filters, **not** actions. Is there any variable like `$wp_filter` or something?
Filters and actions are both assigned to hooks. Functions assigned to hooks are stored in global `$wp_filter` variable. So all you have to do is to `print_r` it. print_r($GLOBALS['wp_filter']); PS. `add_action` function makes a `add_filter` call. And the latter does `$wp_filter[$tag][$priority][$idx]`. * * * NOTE: you can directly add this code in functions.php, and you will see a debug on your site: add_action('wp', function(){ echo '<pre>';print_r($GLOBALS['wp_filter']); echo '</pre>';exit; } );
stackexchange-wordpress
{ "answer_score": 54, "question_score": 40, "tags": "plugins, filters, hooks, actions" }
has_excerpt yields true but no post_excerpt when retrieved echo has_excerpt($att); //Results in True echo $att->post_excerpt; // results in empty. echo $att; // results "782" which is the ID of the attached image. If I use `get_post_meta( $att , '_wp_attachment_image_alt', true)` I get the alternate text but I can't seem to retrieve the caption via `$att->post_excerpt;`.
If `$att` is a numeric post ID, then try this: $attachment = get_post( $att ); echo( $attachment->post_excerpt ); `has_excerpt()` takes a post ID, but the post ID isn't an object. You have to get the attachment using `get_post()`, then get the excerpt from there.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "attachments, excerpt" }
meta fields for the whole wordpress site Is there a simple way to store additional information related to the whole website in a meta field? For users, comments or posts, I learned how to use meta fields to store their additional related information, but sometimes I need to have growing arrays that contain additional information about the whole website. Your clarifications are appreciated.
You are talking about "Options". These are saved in the `*_options` table and can be stored and retrieved using a number of Core functions (straight from the Codex page above): **Add/Delete Option** * add_option() * delete_option() * add_site_option() * delete_site_option() **Get/Update Option** * get_option() * update_option() * get_site_option() * update_site_option()
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom field, options" }
Wordpress Central User Database I run multiple Wordpress sites, I would like to centralize the users table so that users can access all the sites with a single username. Why do this? I run video communities What do I need? User X can access sites a b c d without registering to each website. The question is.. is it feasible? if so how? Can anyone please advice a better aproach of what do I need to achieve this.
WordPress can be used as Network or Multisite install (different words, same topic). There you only got one central database table for all users.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, users, user registration" }
Missing Title on custom post types I missed the title on custom post types on new or edit page; I have added some custom fields, but Title disappeared. register_post_type( 'videos', array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'exclude_from_search' => true, 'query_var' => true, 'rewrite' => true, 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => 10, 'supports' => array( 'editor' ), 'register_meta_box_cb' => 'videos_meta_boxes', ) ); This is the first time I tried to add customs post types on my own. I think something here is missing.
By declaring a value for the parameter 'supports', you override the default output which shows the 'title' and 'editor'. < I recommend removing the 'supports' parameter if you don't need any other post fields (reduce clutter on the page) or just re-iterate the default (in case you want to easily add more fields like thumbnail or comments later): 'supports' => array( 'title', 'editor' )
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "custom post types" }
Which database table does "Featured images" save under? I'm having an issue while upgrading WP from 3.2.1 to 3.5.2, where one section's Featured images have all been deleted. When I visit that section's edit post pages, the featured image thumbnails that were once there are no longer there. Is this a database issue? I just dumped/restored my database an hour ago. I'm wondering if the WP database upgrade deleted my data. Which table do the featured images data go under? I'm wondering if I could just dump/restore that table again, but I don't know which one it is. My images are still there, but the links to them don't seem to exist in the database.
The featured image itself-- the actual `.jpg`, or `.png`, most likely-- is saved to `wp-content/uploads` with primary image data saved to `$wpdb->posts` as an `attachment` post type. Additional relevant data for the image is saved in `$wpdb->postmeta`. What makes an image "featured" or not is an entry in `$wpdb->postmeta` under the key `_thumbnail_id` and a `post_id` field matching the post ID of the post for which the image is a "feature"-- aka thumbnail. It is hard to say where things have gone wrong. It could be any three of those components.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "upgrade" }
Featured image in admin on custom post type I followed this tutorial to getting featured images to show in the admin menu on posts. I wanted to be able to see what article had a featured image and what it looked like without having to actually edit the article. The article worked, but I noticed that it didn't work on my custom post type. So I went looking for the filter that would make it work and found manage_edit-post_type_columns I have a custom post type for "Events". The slug for this is "events". I figured from the codex that if I did this add_filter('manage_events_custom_columns', 'ST4_columns_content', 10, 2); It would work but it has not. I can see the column for the featured image in the admin menu but I do not see the image in the column next to the post.
I tried both codes and they worked for me, first I added this code add_filter('manage_posts_columns', 'bootpress_slider_columns'); function bootpress_slider_columns($defaults) { $defaults['featured_image'] = 'Featured Image'; return $defaults; } and it added column both in custom post type and on posts Then I followed this link manage_${post_type}_posts_columns my post type is "slider" the below code worked for me add_filter('manage_slider_posts_columns', 'bootpress_slider_columns'); function bootpress_slider_columns($defaults) { $defaults['featured_image'] = 'Featured Image'; return $defaults; } in your case the below code should work add_filter('manage_events_posts_columns', 'ST4_columns_content', 10, 2);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, post thumbnails" }
Simple form to add custom links to menu? I currently have a menu set up called "sidebar links" with 5 custom URLs. In my widgets section I have a Custom Menu which shows my "sidebar links" menu. This basically gives my sidebar 5 links. * * * What I am looking to do is to make a simple html/php form which.... * You enter an URL and title then hit enter * The form then adds this URL to the menu as a custom URL * The form then removes the oldest link Is this possible? I don't want to give people access to the menus part of the dashboard.
Well, since you're talking about a widget of Links.... why not just use the default Links widget that was part of core up till 3.5? < If you insist on limiting it to showing the latest 5 links, you're going to have to write a bit of code (that I'm not convinced is worth it). Possible approaches include: * Filtering the output of said Link Manager widget * Creating a custom post type called 'Sidebar Links' and then writing your own widget that displays the 5 latest * Creating a totally custom interface and storage mechanism from scratch (definitely not recommended) Another options is using something like Options Framework (< to add some Theme Options. You could add Link 1, Link 2, Link 3, Link 4, and Link 5 as options. It's not an amazing user interface, but it's another quick way to accomplish basically what you're looking for.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, widgets, sidebar, links" }
do more action after I publish a post I am using `wordpress3.5`, I need to write post information to a file **after** I publish a post successfully. What I am not know is 1. When I click Publish button, what function wordpress invoke to save the post to mysql table wp_posts. I dive into wordpess's code ,found many many php file include. 2. If I want to do more action, what should I do. For example, I want to write the post information to a file. Thanks very much.
There are a number of hooks you can use, such as `publish_post` or `save_post`, e.g.: // an example of a post save hook add_action( 'save_post', 'diligents_post_save_hook' ); function diligents_post_save_hook( $post_id ) { //verify post is not a revision if ( !wp_is_post_revision( $post_id ) ) { // do things } } `save_post` will fire on publish and update, so be aware it will fire on saving of drafts etc. `publish_post` will run on publish, keep this in mind as it will not fire on update. Saving data to a file is a step I cannot cover, as it is not a WordPress question, but a standard PHP question. For details on writing, reading, and saving to files, reference PHP.net
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "posts, query posts, publish" }
How can I show different image links for different languages with qTranslate? I have a set of links, each with an image - how can I show different links depending on the language selected (using qTranslate) - the images have text on them.. At the moment I show these links using the rotating links widget. Are there any plugins to help with this? or do I need to resort to PHP?
You can get the current language with qtranslate using the function `qtrans_getLanguage()`; and then use it like this for conditionally showing content: <?php if ( qtrans_getLanguage() == 'en' ) { //put your code in here } elseif ( qtrans_getLanguage() == 'de' ) { //put your code in here } ?>
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "links, multi language" }
How to get custom image sizes into media uploader dropdown? I searched net to solve the problem with images size uploaded from media. But not even one worked to me. When I try to insert images from the media into post it does not show my custom image size 608 X 350 px function setup_image_sizes() { if ( function_exists( 'add_image_size' ) ) { add_image_size( 'post-image', 608, 350, true ); } function post_image_sizes($sizes){ $custom_sizes = array( 'post-image' => 'Post Image' ); return array_merge( $sizes, $custom_sizes ); } add_filter('image_size_names_choose', 'post_image_sizes'); } add_action( 'after_setup_theme', 'setup_image_sizes' ); please advise me
Try seperating it like this: function setup_image_sizes() { if ( function_exists( 'add_image_size' ) ) { add_image_size( 'post-image', 608, 350, true ); } } add_action( 'after_setup_theme', 'setup_image_sizes' ); function post_image_sizes($sizes){ $custom_sizes = array( 'post-image' => 'Post Image' ); return array_merge( $sizes, $custom_sizes ); } add_filter('image_size_names_choose', 'post_image_sizes'); That way it is working in my setup. Additional Sources: \- custom image size with New Media Manager in wordpress 3.5 \- <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "post thumbnails, images" }
show tags on "single"-template sidebar only If a post has tags, I would like to show only those tags as a list in the sidebar when viewing the single post; how do I do this? I have searched to find a suitable plugin, but didn't find one, as all the ones I've looked up end up showing every tags on the site or for categories. I'm happy to go with a non-plugin solution.
This will display the tags of the current post in an unordered list: <?php is_single() && the_tags( '<ul class="tags"><li>', '</li><li>', '</li></ul>' ) ?> < You'll most likely want to drop this in `sidebar.php`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "tags, sidebar" }
Images uploaded using media uploader are appearing upside down A client of mine has come to me with an issue I've never seen before. Some of the images he's uploaded via the media uploader are appearing upside down or sideways. I'm assuming it's because they were taken on a phone and Wordpress is preserving the direction in which they were shot? Is there a fix for this?
Either one of those plugins should fix the problem: * < * <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "functions, images, uploads" }
Editing <?php the_content('Read more...'); ?> Is it possible to automatically add for example image before first h2 tag in the_content?
Yes, it is possible. You can use `the_content` hook and assign your own filter to this hook. Then you should (that is the part when things get a little bit messy) parse and replace content of that post. So for example you can do it like so: function my_the_content_filter($content) { $content = str_replace('<h2 ', '<img src=""...><h2 ', $content); return $content; } add_filter( 'the_content', 'my_the_content_filter' );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "filters, hooks, the content" }
Theme automatically inserting "more" tag on every post I'm using the free Lensa theme and it seems like it inserts a "more" tag in every single post when viewing by category, and the point at which it inserts it is proportional to the length of the post. < That quote is only about 10 words long but gets truncated after the 6th word or so. I admit I don't have much experience with php, but I'm assuming this should be a pretty easy fix since the code seems to do this universally across any type of post. Any ideas/tips on which files to go through first? What sort of function I'm looking for?
In your archive.php file, you would want to replace this: `<div class="entry-content"> <?php colabs_custom_excerpt(); ?> <p class="more"> <a href="<?php the_permalink() ?>"> <?php _e("More","colabsthemes"); ?> </a> </p> ` With this <div class="entry-content"> <?php the_excerpt(); // or the_content(); ?> </div><!-- .entry-content --> The theme creator is MANUALLY inserting the more button (as you can see). You could just remove the paragraph containing the More button, or replace their custom function with the native functionality (both given). If you plan on updating your theme ever (which I recommend you do), I strongly recommend creating a child theme, which is explained thoroughly here, and do any file/style changes there, instead of the theme itself. Just copy over the files into the child theme and edit there. This way, you won't lose any changes when you update your theme!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, themes, theme options" }
Wordpress Rewrite I'm trying to get < to rewrite to < but I can't for the life of me figure out how to get the url rewrites to work. /site/ is the root directory for my WP installation /vendors/ is a page
assuming `u` is a custom query var, you have to first add it to the array of recognized query vars: function wpa_query_vars( $query_vars ){ $query_vars[] = 'u'; return $query_vars; } add_filter('query_vars', 'wpa_query_vars'); Then add an internal rewrite rule that accepts anything appended to `vendors` and passes that as the `u` query var: function wpa_rewrite(){ add_rewrite_rule( 'vendors/([^/]+)/?$', 'index.php?pagename=vendors&u=$matches[1]', 'top' ); } add_action( 'init', 'wpa_rewrite' ); Make sure to flush rewrite rules once for this rule to be added, you can also do this by just visiting the `Settings > Permalinks` admin page. Then in the template, you can access the value of `u` via `get_query_var()`: $vendor = get_query_var( 'u' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "url rewriting, htaccess, rewrite rules, profiles" }
wp_filter_kses allow HTML5 video? Is there a way to allow my users to add HTML5 video tag (without shortcodes) into my textfield/textarea? Allowed anchor styles and bold tags are working, but as soon I add 'video' and 'source' it doesn't work anymore:( Any help is appreciated. Thx. function validate_setting($plugin_options){ //This Works $allowed_html = array( 'a' => array( 'href' => array (), 'title' => array ()), //This works also 'b' => array( 'style'=> array(), ), //This is not working... 'video' = array( 'width' => true, 'height' => true ), //This also is not working... 'source' = array( 'src' => true, 'type' => true ), ); $plugin_options['text_area']= wp_kses($plugin_options['text_area'],$allowed_html); return $plugin_options; }
Ok This Thread did helped me a LOT! So now my function works (i can embeld HTML5 videos) and it looks like this: function validate_setting($plugin_options){ global $allowedtags; $allowedtags = array( 'a' => array( 'href' => array (), 'title' => array ()), 'b' => array( 'style'=> array(), ), ); $allowedtags['video'] = array( 'width' => true, 'height' => true ); $allowedtags['source'] = array( 'src' => true, 'type' => true ); $plugin_options['text_area'] = wp_kses($plugin_options['text_area'],$allowedtags); return $plugin_options; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp kses" }
Adding [...] string for a custom excerpt function My blog is photo-oriented and the theme has a special excerpt function that, for better or for worse, I'd like to keep using. Anyway, it displays the excerpt and then the "More", but it just completely cuts of the excerpt, which I think looks a bit odd, especially mid sentence. Not really sure what kind of change has to be made here, and would if go into the custom excerpt function itself, or as a separate function called by the excerpt function?
I have a custom except function I use all the time, it will cut off in the middle of a sentence, but it works great. Just drop this baby into your functions.php and then `<?php the_excerpt_truncate(100); ?>` just change the 100 to your desired character limit. // THE EXCERPT MAX CHAR function the_excerpt_truncate($charlength) { $excerpt = get_the_excerpt(); $charlength++; if ( mb_strlen( $excerpt ) > $charlength ) { $subex = mb_substr( $excerpt, 0, $charlength - 5 ); $exwords = explode( ' ', $subex ); $excut = - ( mb_strlen( $exwords[ count( $exwords ) - 1 ] ) ); if ( $excut < 0 ) { echo mb_substr( $subex, 0, $excut ); } else { echo $subex; } echo '...'; } else { echo $excerpt; } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "excerpt" }
How to pass custom parameter to WP_Query for filtering in pre_get_posts I have an ajax request that returns the result of a WP_Query loop. I would like to detect in pre_get_posts filter the specific wp_query instance that is used in the ajax handler. I thought placing a custom parameter in the $args of the WP_Query in the ajax handler: $args= array(..., 'ajax' => 'AJAX',//custom param for detection of specific WP_Query instance ....); and by this way detecting the specific instance in pre_get_post: if(isset($query->query_vars['ajax']){ Do stuff } I do not know if this has any sense to you... Thanks¡¡
You can access query variables (including custom ones) via the `WP_Query::get()` method. For example: $my_query = new WP_Query( array( ... 'wpse105219_custom_var' => 'foobar', ... ) ); To 'catch' this at `pre_get_posts`: add_action( 'pre_get_posts', 'wpse105219_pre_get_posts', 10 ); function wpse105219_pre_get_posts( $query ){ if( $query->get( 'wpse105219_custom_var' ) == 'foobar' ){ //Alter $query } }
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "wp query, ajax, pre get posts" }
Cannot change Connection Information in admin interface There are 11 plugin updates available for a WordPress site, so I tried updating it. However, when I do that I get an error: Public and Private keys incorrect for <username> I have made keys for my own user on the server, but that is not the problem I am asking about. The problem is that I cannot change any details in the Connection Information page (shown below). There are details already there, but they cannot be changed. I can select them, but I cannot delete or edit them. I have tried in different browsers. What could be causing this? My WordPress account is set as an Administrator. * * * !Connection Information
I believe that you have some or all of these defined somewhere, probably `wp-config.php`. define('FTP_PUBKEY', '/home/username/.ssh/id_rsa.pub'); define('FTP_PRIKEY', '/home/username/.ssh/id_rsa'); define('FTP_USER', 'username'); define('FTP_PASS', 'password'); define('FTP_HOST', 'ftp.example.org'); define('FTP_SSL', false); < I am able to duplicate the issue and resolve it by manipulating those constants.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp admin" }
Reset default roles and capabilities I've been having a difficult time adding custom post type capabilities to roles (Adding capabilities to default roles) and I suspect that my muddling around may have caused some problems. I also have installed and de-installed various plugins some of which added capabilities. As a result My WP Role object is a bit of a mess. Does anyone know of a way to reset capabilities or do I need a fresh install?
I use User Role Editor. You can delete added roles, and reset roles from the plugin page. To reset the administator role, you can, as of WP 3.4+, add define('URE_SHOW_ADMIN_ROLE', 1); to your _wp-config.php_ file. After having done so, you need to go to _Users > User Role Editor_ and click _"Reset"_.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 13, "tags": "user roles, capabilities" }
Modifying navigation menu classes with a Walker I did a class that extends Walker_Nav_Menu to modify the default classes of my < li >s but also to modify the default classes of my < ul >s. It seems that only the sub-menus are affected by the Walker. I would like to remove the classes and id of the first < ul > (the menu itself), but the walker won't let me do that. There are some arguments in "wp_nav_menu( array $args )" that will let me change the < ul >'s class and id, but nothing to remove them. I don't want to do: 'menu_class' => '', 'menu_id' => '', and i'm guessing there is a solution to completely remove the class and id.
Use the `items_wrap` argument (see codex). wp_nav_menu( array( 'items_wrap' => '<ul>%3$s</ul>', ) )
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "navigation, walker" }
Localhost wordpress access remote db wordpress website I install wordpress on localhost.
WordPress stores site url and home url in database. And it can have only one value. The easiest way to do it, would be to change these options to localhost address. If you do so, you will be able to work on this WordPress on localhost, but remote installation won't work (it will redirect you to localhost). Another way to do this, is to fake DNSs response and set this domain to point on your localhost. You can do this by editing etc/hosts file, and then setting virtual host on your apache server. I prefer second solution. WordPress will still work on remote server, and by editing etc/hosts file I can quickly change which WordPress will I see.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization, development strategy" }
Where is the right .mo file inside the language repository? I need to translate my Wordpress in Italian. Following the instruction written on WordPress in Your Language, I've searched my .mo file inside the Language Repository but I've some problems. The folder structure is not as expected, there are lots of folders that don't make me any sense: branches/ buddypress/ mu/ rosetta/ tags/ trunk/ I've read the instructions about the repository but they mention just some of these folders. I've tried to find the .mo file opening all the folder, but there are lots of .mo files (for example under branches/3.5/messages) I've searched into some forums but everybody says just "go to the repository and download your .mo file" like there is just one file. What am I missing?
To translate you need few things first in place. 1. Create a directory called languages inside wp-content . 2. Now define your country and locale in wp-config.php file. For example as you wish to translate into italian. You should add these lines. define ('WPLANG', 'it_IT'); 3. Now as you have read on forums you need to put the .po file in languages directory for example This file. This should solve your problem.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "translation, language" }
Limit length of headline in Editor I`m searching for a function to limit the number of characters a user can type into the headline field in the editor.
You could add this function : add_action('publish_post', 'wpse_105297_max_char'); function wpse_105297_max_char() { global $post; $title = $post->post_title; if (strlen($title) >= 100 ) wp_die( "The max lenght is 100 for title" ); } This will prevent users from using too much longer titles.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, editor" }
Does update_comment_meta hook exists? Its been 3 days now I am fighting to resolve the issue here: An action hook where a comment meta is updated I am pretty sure, even if I am a beginner, that the hook `update_comment_meta` doesnt exist, and that it is not possible to use something like: add_action( 'update_comment_meta', 'do_soemthing', 10, 4); Any confirmations, or objections are highly welcomed.
Well, it's a little bit complicated ;) If you will search `update_comment_meta` hook, you won't find it. But it exists :) There is `update_comment_meta` function and it calls `update_metadata` function with first param set to `comment`. This `update_metadata` function does something like this (meta.php line 149): do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value ); where `$meta_type` is the first param of this function. So it will be `update_comment_meta` when this function is called by `update_comment_meta` function (because `$meta_type` is then equal to `'comment'`).
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "hooks, actions" }
Create custom markup to use in posts? Is there some way - a plugin, a technique, some file to edit - to define some custom markup to be interpreted, parsed and replaced with custom, generated content when generating posts? The simplest example of what I want would be smileys, getting a `:)` or in text of the post replaced by a specific `<img scr="...">` when generating the HTML, or custom version of BBCode, but in my case the generated content would be more complex, at the very least requiring the use of the post ID, but probably more, so I'd prefer a PHP-side solution working somewhere under the `the_post()` surface, not a simple client-side Javascript rewriter.
You are probably looking for The Shortcode API that allows to create shortcodes like `[my_shortcode]` and `[my_shortcode]some text[/my_shortcode]` to be used in content and other shortcode-enabled areas. More advanced technique are way more involved and might require storing editable and rendered representation of content separately or do apply custom rendering filter every time content is displayed.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "html" }
Problem with trying to display subheader in posts On this article, it was said that you can use the `h4` tag to create a subheader to break up long posts. However, whenever I wrap text in the tags, it displays the tags as regular characters. Wordpress doesn't seem to recognize the use of HTML. I have this Hello... blah blah <h4>And there was freedom!</h4> But it renders exactly the same, with no header. I am using the theme December if that has anything to do with it
You easily add an H4 tag in the "Visual" version of the editor (the tab on the upper right corner of the editor) by selecting the text you want to be the subheader at the top of the rich text editor there is a buttom at the end of the first row of icons called the "Kitchen Sink", click this to expose all the options the editor has available, now select the drop down hich likely says "Paragraph" and change it to "Heading 4". If you are on the "Text" version of the editor, you would add the `<h4></h4>` tags around your subheading.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts" }
Previous and Next Navigation buttons take the user to the wrong posts I am currently developing a portfolio section on my website and when the single posts are viewed, there are some previous and next links to take the user to the next post. Upon reaching the first post single view, the previous button takes the user to the fifth post in the series rather than looping to number 12 in the series as expected. Here is the code I used to generate the previous and next buttons, <div class="five columns portfolio-nav"> <ul> <li><?php previous_post_link('%link'); ?></li> <li><a href="<?php echo get_permalink( 187 ); ?>" class="backportfolio">My link</a></li> <li><?php next_post_link('%link'); ?></li> </ul> </div> the portfolio test site is at < Is there a way of configuring these buttons to allow them to move to the appropriate post
You could try the following plugin: * < It is very customizable in terms of link options and should, as far as I can see, do the job for you. I have very good experience using it up to WP 3.5.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "previous post link, previous" }
Make homepage the newest post of a custom post type I am using the plugin "Custom Post Types" to create an issue based magazine, where one of my types is "Covers." There will be one of these posts for each issue and will include the cover art and an list of articles in the issue. My question is, how can I make the main page default to display a single view of the newest post of this type?
Create a `front-page.php` file in the theme and query for the latest post of your post type. $args = array( 'post_type' => 'yourtypename', 'posts_per_page' => 1, 'ignore_sticky_posts' => true, 'post_status' => 'publish', } $latest = new WP_Query($args); if ($latest->have_posts()) { while ($latest->have_posts()) { $latest->the_post(); the_title(); // etc } } See the Template Hierarchy for information about files that are "automagically" loaded..
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types" }
Does wordpress insert automatic google analytic? I just noticed there was this script in my source code: <script src='/google_analytics_auto.js'></script> I did not insert this script and I have no plugins, so I don't know why it's there? Does someone know how to remove that?
The reason is you are using HostGator and enable the feature is Google Analytics Integration, by enable this one, HostGator will automatically add this snipped of code into your main website and all of it sub or add-on domain: <script src='/google_analytics_auto.js'></script></head> I my self also faced with this issue, my main website is < and I got the above line of code when viewing source, I tried to have one fresh Wordpress in my add-on domain, but it still be there. After I tried to install wordpress on my local (by using XAMPP) then I found out the root cause is Google Analytics Integration of HostGator. You just going to cPanel, choose the Google Analytics Integration, at the configuration you just choose to uninstall the Google Analytics (UA) for your domain and it will work.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "google analytics, google" }
How can I remove categories in menu in custom post type? I'm creating a custom post type and have added categories taxanomy. This can be done in two ways: // In $args array 'taxonomies' => array('category'), // or calling a function register_taxonomy_for_object_type( 'category', 'my_custom_post_type_name' ); In both cases, an additional child-menu item appears in my custom post menu in the left admin menu. Categories are already showing under `Post` menu, so I don't need it to display again. Any way of preventing this?
This was hacked together very quickly. I don't for sure if there will be problems with translation, but I be there would be. function remove_menu_from_cpt() { global $submenu; $post_type = 'book'; $tax_slug = 'post_tag'; if (isset($submenu['edit.php?post_type='.$post_type])) { foreach ($submenu['edit.php?post_type='.$post_type] as $k => $sub) { if (false !== strpos($sub[2],$tax_slug)) { unset($submenu['edit.php?post_type='.$post_type][$k]); } } } } add_action('admin_menu','remove_menu_from_cpt'); It used the 'book' post type and post tags, because that was convenient for me to test, but it pretty obvious what needs to change to make this work for your case-- I believe you need: $post_type = 'my_custom_post_type_name'; $tax_slug = 'category';
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "custom post types, customization" }
WP_Error not displaying errors I am trying to utilize WP_Error for my plugin, but nothing happens. Is this too late for WP_Error? Too early? Or am I doing something else wrong? function cpt_pre_post_publish(){ return new WP_Error('error', __('Error!' )); } add_action('pre_get_posts', 'cpt_pre_post_publish');
Actions don't typically `return` data, so I doubt you will get this working the way you are trying to. Something like... function cpt_pre_post_publish(){ global $my_error; $my_error = new WP_Error('error', __('Error!' )); } add_action('pre_get_posts', 'cpt_pre_post_publish'); ... should set a variable that you could access in a template file with... global $my_error; var_dump($my_error); It is really not clear exactly what you are trying to do though.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "pre get posts, wp error" }
How can I sort homepage by a meta value? I am trying to sort my home page posts by a custom meta value. I've been told I should use `pre_get_posts` but I seem to not be implementing it correctly. This is what I am doing: add_filter('pre_get_posts','alter_query'); function alter_query($query){ if( $query->is_home() ){ $query->set( 'meta_key', 'key name' ); $query->set( 'orderby', 'meta_value_num' ); $query->set( 'order', 'DESC' ); } return $query; } When I use the above function, the homepage query is not returning all the posts and not ordering them properly; I am trying to figure out if it I am going about this the correct way.
You probably also need: $query->set( 'ignore_sticky_posts', true ); That will prevent sticky posts from shuffling to the top. Maybe: $query->set( 'posts_per_page', -1 ); If you are getting too few posts. `-1` means "all". You can use that to change to a number other than what is set in the backend. A couple of notes: 1. `$query->set( 'meta_key', 'key name' );` will limit the results to posts with that `meta_key` 2. If your `meta_value` for the `key name` isn't really a number the order isn't going to work correctly. Punctuation and letters will mess this up. 3. `is_home` can be peculiar. Make sure it does what you need it to do. Beyond that, you will need to explain "not returning all the posts and not ordering them properly" in better detail.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom field, query posts, query, post meta" }
theme upgrade failing The twenty eleven theme fails to update. The error message is : failing to delete old theme. For security reasons i dont want to give rights to every folders of the project. What are the folder to give rights to for that action?
You can update the theme via cPanel by: 1. Browse `wp-content/themes/` using the file manager 2. Rename the folder named 'TwentyEleven' to 'TwentyEleven.Backup' 3. Download a fresh upgrade copy of T11 from WordPress.org theme repository 4. Upload the `.zip` theme file (what you just downloaded) 5. Extract the `.zip` file (it will make the folder 'TwentyEleven' again) 6. Your upgraded theme is ready Hope it will automatically activate itself; if not, then in `wp-admin`, browse `Appearance` > `Themes`, and then reactivate (or deactivate and activate) Twenty Eleven theme. **WARNING:** Upgrading a theme, by all the default and automatic means, will delete all the modifications and edits of codes, if made any.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "updates, theme twenty eleven" }
Integrate WordPress in Yii I'm developing a web application in Yii, now the client wants to integrate WordPress in it so he can manage contents on his own. So how can I integrate WordPress in Yii?
I don't have any experience with Yii, but looking at their Wiki there are already some solutions: 1. Integrating Wordpress and Yii,Working Out The Details. 2. Integrating Wordpress and Yii: still another approach, using Yii as the router/controller 3. Integrating Wordpress and Yii: yet another approach 4. Integrating Yii with Wordpress 5. Run an Yii Application inside an Wordpress page Please take a look at the above 5 links, they probably contain a suitable solution for you.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php" }
How to prevent tinyMCE editor to be loaded completely in Text Editor? I'm working on a theme. Part of which there are editing modes: * Syntax-new mode using CodeMirror * the two native modes (Visual and Text editor) I have an odd scenario that tinyMCE is loaded on text editor, so that means the buttons, etc. resembles like the Visual editor. Is there a WP hooks that I can use to prevent it from loading completely in the text editor? I only need to use the native Text area without these tinyMCE functionality.
This is a working for me: //Sets HTML as default editor add_filter('wp_default_editor', create_function('', 'return "html";')); When the page is loaded, it will always use text editor as default, removing extraneous buttons for tinyMCE.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, tinymce" }
Image menu on responsive WordPress 1) Why WordPress only use based on "text" menus (navigation) only? Maybe the answer is "it is for SEO and mobile responsive WordPress". Am I correct? any other opinions? 2) What if I create "image navigation menu" for only PC version and create "mobile navigation and responsive" maybe select box. Is it possible? I have found `is_mobil()` and I think it can be done. Please see this link `http:www.tourtips.com/` and see the beautiful image navigation menu. I really want to use it but I worry about mobile version. Is there any way to keep this image menu for PC version and create another mobile or small size menu for smaller devices? if it's possible, what codes I should use? I think some of codes should be loaded depends on devices such as: `if...is_mobile()...` and CSS parts... and loading scripts... Any more things I should worry? any tips? any tutorial links?
I'm not sure what you are asking for, but I think you need some general suggestions. So: 1) **Websites are made bythree layers**. Wordpress (like others good CMS) creates "only" TEXT menu because this is the (fundamental) semantic layer. 1-b) Then, you can always add a presentation layer (css) or a behaviour layer (javascript) in order to create an Image menu, also if Wordpress gives you just the semantic layer. You can reach this with some techniques, one of these is the **image replacement technique**. 2) If you have understood the two points above, you can also understand that **is not so useful to generate on the server side two different html**. All that you need is to create a good semantic HTML (Wordpress does it!) and after, via css and javascript, you can add all your images and behaviours.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, navigation, responsive" }
rewrite rules add a folder in the path I have to do some url rewritting for custom post types. I have 2 custom post types: _portfolios_ and _locations_. What I need to change is the url like this: current: Should change to: current: should change to: How can I use `add_rewrite_rules`? Would it be better to use `generate_rewrite_rules`?
I think that portfolios and locations are two custom types right? In this case you have to change the slug options inside the custom type registration: register_post_type( 'portfolios', array( ... 'rewrite' => array("slug" => "/production/portfolios", "with_front" => false), ) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, url rewriting, rewrite rules" }
Show that current post is number X out of X Is it possible to echo at the end of a post which number the current post is? For example; Say you're viewing the 4th most recent post out of a total of 10, somewhere at the foot of the post I need it to say **"Post 4/10"**... Is that possible?
I would do this with `$query->current_post` and `$query->post_count` with `$query = new WP_Query(args);`. With this you may get the position and the total of posts.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "posts, count" }
Extracting gallery images in Wordpress 3.5 on index.php I'm trying to add a slider on my front blog page for every gallery post, but I have some trouble extracting the images from the post gallery, using the following code: $post_content = get_the_content(); preg_match('/\[gallery.*ids=.(.*).\]/', $post_content, $ids); $array_id = explode(",", $ids[1]); The problem is that each gallery post consists of paragraph with text, "read more" break and a gallery after the break and thus **get_the_content()** skips the images because they are after the break. How can I make it get the whole content, regardless of breaks? I use "read more" because I want short description about the gallery post before clicking on it to read it.
`get_the_content` is a template tag and would only work reliably inside a Loop. That means that you should also be able to use the `$post` global instead. global $post; // may not be necessary unless you have scope issues // for example, this is inside a function $post_content = $post->post_content; preg_match('/\[gallery.*ids=.(.*).\]/', $post_content, $ids); $array_id = explode(",", $ids[1]); You can then use `wp_get_attachment_image` to actually get the images. foreach ($array_ids as $id) { echo wp_get_attachment_image($id); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "images, gallery, the content, read more" }
"Custom Post Type Permalinks" plugin URL strcuture I've found this great plugin _Custom Post Type Permalinks_ by a Japenese developer which is awesome at generating hierarchical permalink structures for Custom Post Types. Only I'm having an issue which I cannot get around and am looking for a solution. I have a custom post type `classes` and a taxonomy `classes_categories` (ex: languages, technology, sciences...) The links generated by WordPress for the 'classes_categories' look like this: I would like them to be like this: Strangely, both of the URL's work but I would like WordPress to generate them without 'class_categories' in the URL. I'm looking for a solution which would involve either plugin configuration, my taxonomy declaration parameters or perhaps a workaround with a hook or something (maybe parse the URL when they a being rewritten). thank you
I managed to find a way to fix this by toying with my Custom Post Type and Taxonomy registrations. In `register_post_type` properties: 'rewrite' => array( 'slug' => 'classes' ), In `register_taxonomy` properties: 'rewrite' => array( 'slug' => 'classes', 'with_front'=> false ), I now have a clean structure where ` points to the post type archive template, ` points to the taxonomy archive template and ` points to the post template
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, custom post types, custom taxonomy, permalinks" }
Is there an action/filter called when WP_Query->query is finished and assigns posts I took a look at the `WP_Query->get_posts()` function and couldn't see any action/filter that is called **AFTER** a query finishes. I want to be able to manipulate the results once they are sent, rather than the query itself (Using a Human Name Parser to sort by last name). I'm revamping an old site that alters the global `$wp_query->posts` right within `archive.php`, so I was just wondering if there was a way to take this logic completely out of the archive file and store it with my other CPT functionality. Cheers!
The is the `the_posts` filter, which sounds like what you want. function filter_the_posts($posts) { var_dump($posts); } add_filter('the_posts','filter_the_posts');
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "wp query, actions, customization" }
Create a select drop down of available menus I'm attempting to create a custom field on my page creation that allows a user to choose which menu to display on the page. Right now I have my custom meta field setup, but can't figure out how to make a drop down menu of the available menus. Is there a function that I could use and then for loop though? Thanks!
It is not intuitive but `get_terms` will do it, if I understand what you need. var_dump(get_terms( 'nav_menu')); If you look in the `*_term_taxonomy` table you can see why. The menus are stored as a taxonomy named `nav_menu`. This won't get you things like page menus, only the intentionally created menus.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom field, menus" }
wp_enqueue_script does not work I am developing a child theme based on the roots theme. I created a **front-page.php** and added the following. I test that the page is loaded because I see the I am loaded text. However, the scripts are not loaded. What is wrong with my setup? <?php function dd_register_scripts() { wp_register_script( 'something', get_template_directory_uri() . '/assets/js/something.min.js', array('jquery'), null, false ); } function dd_enqueue_scripts() { wp_enqueue_script('something'); } add_action('init', 'dd_register_scripts'); add_action('wp_enqueue_scripts', 'dd_enqueue_scripts'); ?> <div id="asd">I am loaded</div>
Based on your description that you "created a `front-page.php` and _**added the following**_ " and also that there is markup in that file, you are hooking too late. You should be both registering and enqueueing on `wp_enqueue_scripts` but that isn't the problem here. The problem is that by the time you try to hook, the hooks have already fired. `init` will fire before your templates load at all and `wp_enqueue_scripts` will fire in the page header, which is before this code runs (or you have very broken markup). You can't `hook` to a hook after it has fired. You need to add this code to the theme's `functions.php` with the appropriate template tags to conditionally load the scripts. # Related: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "theme roots" }
How to modify Media Library images DPI [ image quality down to make small in size ] I wonder if there any code or hook out there to manage the image DPI, for example when we use photoshop or other image editing software we use export and image quality to 0-100%, now i am looking for a plugin or code to define the media library'r image DPI to make them small in size. This is i want store two version one with smaller size[DPI] and one for HD quality. Anyone Can help ?
DPI (as saved in image metadata) does not really apply to displays since pixel density is property of hardware. You can fake this by resizing image with smaller dimensions in HTML, but saving with higher JPEG compression might make more sense. Default compression level WP uses is `90` (out of 100) and it can be modified by filters: * `jpeg_quality` (this seems to be legacy one) * `wp_editor_set_quality` (in new `WP_Image_editor` class)
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "post thumbnails, media library, images" }
What exactly is the description field when uploading an image? This is a really basic question and I am slightly embarrassed I do not know, but what exact purpose does the description field serve, when uploading an image with Wordpress? Typically when uploading an image I include a title (maybe) and some alt text. I always thought alt text was to help people with disabilities, so I try to always include it; I usually copy the alt text to the description (which I think would be bad practice), but I can't seem to 'see' the description text anywhere (whilst viewing source). Is it the same as `longdesc`? Any help is appreciated!
If you click through to an attachment page-- `?attachment_id=123`\-- the Description works something like the post body of a normal post (which is basically what it is if you look at the database), or like a long format caption. Of course, I am sure themes can alter that. I am not sure where else, if anywhere else, the description shows up by default. A theme or a plugin could use the information for other purposes.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images, html" }
Category not being selected I'm trying to build multiple loops for different parts of my page but I can't isolate a category. I just get to see every post the category is ignored. Below my code, any suggestions would be greatly appreciated as I'm somewhat at a loss what I'm doing wrong. Thanks! <div id="postblokcontainer"> <?php $first_query = new WP_Query('cat=Postblok'); while($first_query->have_posts()) : $first_query->the_post(); ?> <article id="postblok"> <h1><?php the_title(); ?></h1> <h3> </h3> <?php the_content(); ?> <ul class="socmed"> <li><img src="<?php bloginfo("template_url"); ?>/images/mockup.jpg"></li> </ul> </article> <?php endwhile; ?> <?php wp_reset_postdata(); ?> </div>
The `cat` parameter takes an ID and not the category name or slug. If you want to use the slug you need `category_name` but it must be the slug. $first_query = new WP_Query('category_name=postblok'); Other category parameters are: cat (int) - use category id. category_name (string) - use category slug (NOT name). category__and (array) - use category id. category__in (array) - use category id. category__not_in (array) - use category id.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query" }
Why is my comment feed broken? Here is my site. According to the WordPress codex, my comments feed should be Indeed, every post has that link in its header. However, it's broken. If you click on that link, you'll see that loading it returns a completely blank page. My first question is, can anyone help me work out why it's broken? Second, is there a good reason to keep the comments feed? Obviously the posts feed is important for a blog, but a _comments_ feed?
A "feed" is just another view of the site, really. If there's no matching items, then you'll get a 404 and an empty "view". This view can be expressed as a "no items found" on the front end of the site, while it will be an empty feed if looking at a feed view. Since you had no comments, the query matched nothing, resulting in a 404 header status and an empty feed (which was a correct feed and viewable if you did a view-source on it).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "feed" }
How to get the cropped image from media library? i have the url of an image (full size). During the upload it already generates a smaller version (i added this in functions). How can i get this cropped version when i have the full size url? The Image is not in a post so i can't use post-thumbanil() The image is in a slider on the Homepage
Get the attachment ID for the image, then get the post meta field `_wp_attachment_metadata` for it. This is a serialized array. The field `sizes` in that array contains all available image sizes. Pseudo-code: $sizes = array(); $attachment_url = ' $attachment_dir = dirname( $attachment_url ); $attachment_id = get_attachment_id( $attachment_url ); $attachment_meta = get_post_meta( $attachment_id, '_wp_attachment_metadata', TRUE ); $sizes[] = $attachment_url; // main file if ( ! empty ( $attachment_meta[ 'sizes' ] ) ) { foreach ( $attachment_meta[ 'sizes' ] as $size ) $sizes[] = "$attachment_dir/" . $size[ 'file' ]; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images, attachments" }
Exclude post type with pre_get_posts? I am using pre_get_posts for a custom taxonomy archive display. Now I added a post type 'photo' sharing the same taxonomy with default post type. How can I exclude 'photo' posts being fetched by the taxonomy archive loop by updating my existing function? function my_breakfast_query ( $query ) { // not an admin page and is the main query if (!is_admin() && $query->is_main_query()){ if (is_tax( 'food', 'breakfast' )){ $tax_query = array( 'relation' => 'OR', array( 'taxonomy' => 'category', 'field' => 'id', 'terms' => array( 366 ) ), array( 'taxonomy' => 'food', 'field' => 'id', 'terms' => array( 364 ) ) ); $query->set('tax_query', $tax_query); } } } add_action( 'pre_get_posts', 'my_breakfast_query' );
I found a solution to this myself. It returns the default post type posts instead of excluding the custom post type which is fine for my needs. function my_breakfast_query ( $query ) { // not an admin page and is the main query if (!is_admin() && $query->is_main_query()){ if (is_tax( 'food', 'breakfast' )){ $tax_query = array( 'relation' => 'OR', array( 'taxonomy' => 'category', 'field' => 'id', 'terms' => array( 366 ) ), array( 'taxonomy' => 'food', 'field' => 'id', 'terms' => array( 364 ) ) ); $query->set('post_type','post'); // Added this line to get a working solution $query->set('tax_query', $tax_query); } return $query; // Added this line to get a working solution } } add_action( 'pre_get_posts', 'my_breakfast_query' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "pre get posts, tax query" }
display custom field from inner blog in the main homepage of wordpress multisite I'm using wordpress MU network and I have the main site and all the inner blogs. as people may know it is very hard in wordpress MU to make "relationship" between the main site and the inner blogs. also there is not enough information and soutions on the web regarding wordpress MU unfortunately. (also posted this question and no one ever responded) anyway, in order to display some values from the inner blogs in the main site's homepage I had to use this plugin: < which does pretty nice work but not perfect. anyway, what I am trying to accomplish is to create a simple custom field, use it in the post editor of one of the # inner # blogs and display the value in the main site's homepage.. does anyone know how to do it? Thanks
Use `switch_to_blog( $new_blog_id )`, use `get_post_meta($post_id, $key )` to get the value of the field, and run `restore_current_blog()` when you are done. You could use a site option (`add_site_option($option, $value)`) and store the values you need in an array there in addition to the post meta field. This would save the rather expensive `switch_to_blog()` calls.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom field, multisite" }
WordPress Images | How to get the cropped image? I have the URL of an image (full size). During the upload it already generates a smaller version (I added this in functions). How can I get this cropped version when I have the full size URL? The Image is not in a post so I can't use `post-thumbanil()`. The image is in a slider on the Homepage.
if you have the attachment (image) id, you ca use : wp_get_attachment_image_src( $attachment_id, $size); where $size is the smaller version you want. (see < If you don't know the attachment id you may query the database for full image size url : <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images" }
Not Being Indexed by Search Engines Is there a specific criteria based on which search engines index/not index your site/blog? If my whole blog (2/3 pages-10-20 posts) is not indexed(WordPress), what can I do? My blog has is not indexed by Google/Bing. Any suggestions.
This is a bit of a guess but there is a setting in the backend that will discourage indexing. !enter image description here Make sure that is not checked.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "seo, google search, noindex" }
Is WordPress' is_user_logged_in() secure? I've been wondering about this for a while. Is the following `if` statement safe enough? Is it easy to break through the code and get access to the content when not logged in? <?php if ( is_user_logged_in() ) { // SECURE CONTENT } else { // LANDING PAGE } ?>
Well, you have to ask yourself "Secure enough for what?" I doubt you are a bank or other institution that needs exceptionally high security. If you were you'd a team of $100,000+ per year experts to answer this question for you. With that in mind... You'd have to subvert the WordPress login system to get past that code. I am sure that is possible but if your passwords are solid it should be pretty difficult. It isn't going to be a "put a null-byte in the query string" kind of a hack. It should be secure enough for most purposes. On thing to worry about is that both `is_user_logged_in`, and `wp_get_current_user` upon which it depends, are both pluggable (nonsensically so to my mind) meaning that a malicious plugin, or just a badly written one, could completely destroy your security.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 4, "tags": "user roles, user access" }
"Blog pages show at most" in The Loop I remember in another theme I did, that the The Loop automatically looped for the number that was set in "Blog pages show at most" (Settings->Reading). The theme I am working on right now does not see to consider this number and loops for an infinite amount of time (and crashes of course). How do I make it to consider "Blog pages show at most" ?
The only reasonable guesses that come to my mind are that the theme (or a plugin): 1. Modifies the main Query with a filter on `pre_get_posts`, so look for that filter. 2. Just creates a new Loop with `new WP_Query($args)`. You will have to dig through the template file to find out. 3. Interrupts the `post_per_page` save process or alter the `posts_per_page` option in the database, so check the `*_options` table for the `posts_per_page` key (option_name) to rule that out. 4. The Loop is not calling `the_post`. Without that, the Loop will never increment to the next post and the loop will run until the browser gives up. I'd bet on #1, then #2, with #3 being a distant third. Without more information I can't give a solid answer. Item #4 is a very viable option but the problem is not the query itself but the Loop.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop" }
Change Woothemes admin url I would like to change the next url: `wp-admin/admin.php?page=woothemes` I would like that " **woothemes** " to be anything else. Is that possible without breaking the site?
While WP API probably _would_ allow to move it quite cleanly (there are some plugins that shuffle pages around for different purposes) it is very hard to say if it will just work without complete audit of relevant code for how it uses the page, how it generates link to it and if it will break when it is done. It doesn't help that admin menu is considered one of the most unpleasant corners of WP code base to work with.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "plugins" }
get_stylesheet_directory() returns wrong URI... localhost/using vhosts I'm trying to develop a WP theme for a client via localhost. I'm using XAMPP on Windows 8 and has set up vhosts to something like myclient.dev. This works for stylesheet <?= get_stylesheet_uri(); ?> But when trying to use `get_stylesheet_directory()` (Mainly for images) I get the wrong path: So <img class="logo" src="<?= get_stylesheet_directory(); ?>//images/logo.png"> The src returns: How can I fix this?
As I was getting at in comment: * `get_stylesheet_directory()` produces local filesystem path * `get_stylesheet_directory_uri()` produces URL Just use latter. :)
stackexchange-wordpress
{ "answer_score": 5, "question_score": 6, "tags": "theme development, directory" }
Correct way to make a title a link I made the title of my post excerpt a link to the full content. It works but whenever I validate my website, the validator marks it wrong and shows the message below. I've switched around the h2 tags and it still didn't help. **document type does not allow element "h2"** The code looks as shown b elow <span class="home-post-header"> <a href="<?php echo get_permalink(); ?>"> <h2><?php the_title(); ?></h2> </a> </span><!-- End Home Post Header -->
Nice one for using WordPress, but this is a straight-up HTML question. Nontheless... <div class="home-post-header"> <h2> <a href="<?php the_permalink() ?>"><?php the_title() ?></a> </h2> </div> `h2`'s are considered block-level, whereas `a` & `span` are inline. Standards dictate that a block-level element cannot be nested inside an inline one. So use a `div` instead, & place the `a` _inside_ the `h2`. N.B: With HTML5, nesting block-level elements inside `a` is valid, but IMO use only when you need to wrap a link around several elements (for example, a heading with an image or snippet).
stackexchange-wordpress
{ "answer_score": 2, "question_score": -2, "tags": "theme development, links" }
Custom Query for searching through custom fields Just wondered if someone could spare 5 mins to help me understand where I might be going wrong. I have a set of custom fields for jobs - I would like to create two drop down menus as a quick search: Categories for example - IT, Warehousing, Sales... Salary - 20-30k I have cobbled together this query - $myquery = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT meta_value, post_status FROM $wpdb->postmeta, $wpdb->posts WHERE meta_key = %s AND post_status IN ('publish') ", $metakey)); With this query, it does populate a drop down list, however, it's still including 'drafts' - in the drop down. So, how would I exclude 'draft pages' from populating the drop down? Many thanks Andy
I think you need a join. $myquery = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT meta_value FROM $wpdb->postmeta INNER JOIN $wpdb->posts ON $wpdb->postmeta.post_id = $wpdb->posts.ID WHERE meta_key = %s AND post_status IN ('publish')", $metakey ) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "query, wpdb, dropdown, post status" }
How a deprecated function can crash WordPress site while upgrading It is said that deprecated functions used in plugins & themes can crash a wordress website while upgrading to newer version, I want to see an example of deprecated function that can cause a crash. Can someone show me an example? Many Thanks!
## Where... The following files hold the deprecated functions: * `~/wp-includes/deprectated.php` * `~/wp-includes/pluggable-deprectated.php` * ... Take a look at them and then through their replacement functions, where the calls to `_deprecated_function()` happen. ## Why... Normally a crash shouldn't happen. In the "real" PHP world, you'd get an `E_DEPRECATED` Warning. In WordPress you'll get a `trigger_error()` return caused by `_deprecated_function()` calls. The second `trigger_error()` argument isn't used, so it defaults to `E_USER_NOTICE` and won't stop your application from running. ## How to turn it off... You can turn this off either by using `define( 'WP_DEBUG', false );` or by using a MU-Plugin that sets the filter to false: <?php defined('ABSPATH') or exit; /** Plugin Name: (#105686) Turn off deprecated Warnings */ add_filter( 'deprecated_function_trigger_error', '__return_false' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugin development, upgrade, deprecation, compatibility" }
Plugin used only on some pages - not widget Im using 'Cool FB like' plugin which displays a css fixed facebook logo on the right. When we hover that logo, fan page box is showing up. The problem is that I need to change fanpage on some pages. Do you have any idea how to manage that? I have an idea - I can use one plugin on some pages and another - similar one, on others but this plugin isn't a widget so i can't set where to display plugin up. Maybe You have some other ideas? Cheers
I solved id by myself. For those who want do the same trick: go to bliss-facebook-likebox plugin folder, edit cool-fb-likebox.php. Near the bottom of file there will be an $url variable. Change: $url = urlencode($get_cfbl_options['fbpageurl']); to: wp_reset_query(); global $post; $site-id = 1; // use your own needed number if( is_page($site-id) || $post->post_parent == '.$site-id.') { $url = urlencode(' } else { $url = urlencode($get_cfbl_options['fbpageurl']); //editable in plugin options }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, facebook" }
get_posts always returning the same number of posts = 5 I don't understand why the code below is always displaying the same number of returned post = 5. When I change the `$variable` value to another `post id` of a post with an author with another `author_id`, I always get 5 returned posts, even if the authors have tens of posts. What am I doing wrong? $variable=328; $post = get_post($variable); $author = get_userdata($post->post_author); $args = array( 'author' => $author->id ); global $post; $myposts = get_posts( $args ); $count= count($myposts); echo '<pre dir="ltr">'; print_r($myposts); echo '</pre>'; echo $count; Your help is really apprecieted.
`get_posts()` has some defaults set, including `numberposts` equal to `5`. Since it's not considered to be a loop by itself those are independent and not affected by admin settings. So simply pass in arguments `numberposts`/`posts_per_page` (same thing) number for how many posts you want or `-1` for all matching posts.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp query, get posts" }
White spaces in username give 404 on author page As the title says. When users register with white spaces in their usernames, if you try to go to their author page, you get a 404 error. Is there a way to fix the redirect? or should I add a filter to prevent the use of white spaces in usernames? The site is new, so it wouldn't be hard to just change the one author with the issue. I would think Wordpress would prevent people from having white spaces in their username.
Spaces are not allowed in URLs, so WordPress uses the `user_nicename` for those links. The user `nice_name` is "A string that contains a URL-friendly name for the user. The default is the user's username.". That is a transformed user name such that it is all lowercase with spaces replaced by dashes. I did not look up what other transformations are probably occurring. Whatever is creating those links is doing it wrong. Without seeing the code that creates the links, it is hard to say more.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "user registration, username" }
Use WP_Query or query_posts() or get_posts() for optimizing a site? I have read other answers, but I don't understand which is more fast (the best and simple for slow server running)? I have a website with over 1 000 000 hits /day and a slow server with limitations at database connections, so I want to optimise my site. What do you recommend me to use: WP_Query or query_posts() or get_posts()? And if I want to show articles in different positions, with different styles can I repeat the function [WP_Query or query_posts() or get_posts()] on every article that I show, or it is best to use it one time and use if $i == 1,2,3 for different styles?
This answer explains the differences. They all use `WP_Query`, all parameters being equal there is no difference in speed, it's just a question of which is easier for you for your particular needs (hint: it will never be `query_posts`, which should basically never be used). You should query the database as few times as possible, so if you can fetch all your posts with a single query, then do some manipulation via php to get the output you need, that is definitely what you should do versus creating multiple queries. Note that a `WP_Query` object contains some helpful vars to assist in output, like `$query_object->post_count` and `$query_object->current_post`. You should also be employing a cacheing plugin, like W3TC, if server load is an issue.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, query posts, get posts" }