INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
avi mp4 flv video player I want to uploads videos from admin and show them using any video player. I used a plugin but when i tried uploding a video the message appers that uplod size exceeded. Can anybody suggest me any good video player plugin.
You will need to increase your media upload limits in your php.ini file or ask your host to increase them. You can also increase the limits via your functions file or .htaccess file. Installing a video plugin won't increase the limits. You can also use the native video player already included in WordPress without the need to install a plugin. Paste the full URL to the video on its own line in your text editor.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, video player" }
Video shortcode - autoplay all videos How can I autoplay all videos added by video shortcode? I can make only one of them autoplay if only one has autoplay attribute set to 1, and others to 0, otherwise all are stopped.
I have done this with my own video shortcode, in which i changed classes, so I can initiate player with `$('.my-video-shortcode').mediaelementplayer( {pauseOtherPlayers: false} );` It does what I needed :)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "shortcode, videos, video player" }
Text under post title on frontpage but don't want it in full post On the frontpage of a blog I want a piece of text (like an excerpt) under the title but I don't want is showing up in the full post. Any ideas how I would go about this? EDIT: Wasn't precise enough in my question. The piece of text under the title will be different for every post and has to be able to be set in the backend by the end user, preferably when typing the post.
Tested this and it worked perfectly on Genesis. You can also use HTML tags in the custom field. add_action( 'genesis_entry_header', 'content_after_archive_title', 15 ); function content_after_archive_title() { if ( is_home() && genesis_get_custom_field('after-title') ) : echo '<div class="after-title">'. genesis_get_custom_field('after-title') .'</div>'; endif; } Uses the native custom fields meta box which you can reposition under the Editor. !enter image description here You could also hand code a meta box for this using the `edit_form_after_title` hook if you want the box before the editor or use a plugin like ACF. If your theme doesn't include a hook for the title or post info meta, you could use the content or post meta filter or action hook instead. **Change Position:** If you want it before the post info, simply change the 3rd parameter to 11 and here's the result: !enter image description here
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "title, excerpt" }
Adding custom Bulk Actions I have been looking around for ways to add custom Bulk Actions to the categories page. Most of them say that it is impossible to do it in a clean way, because of the lack of a hook for this. Most of the solutions include using JS in the client side to add the options though DOM manipulation. While this works, it is still quite an ugly solution. Most of the articles I have been reading are about 2 year old, so I was wondering since then to the present a new hook or solution has been added to this problem, to have a more up-to-date solution to this problem.
Unfortunately it's still not really doable in a clean way. You can see the latest about this here in this trac ticket #16031 I just checked the source and the filter is still basically the same.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "hooks, actions, bulk" }
add_theme_support('my-custom-feature') According to the codex, there is no way that I can see to define a custom theme support feature. Ideally, I'd like to set a feature in my child theme that the parent theme could check for. Does an equivalent function exist that would be appropriate to use in this context? For example, I'd like the parent theme to have a new sidebar in the header area, but since I'm introducing this sidebar area late, its presence could break previously created child theme layout look and feel. So, for new child themes created after this addition, I'd like to be able to call something like: add_theme_support('header-sidebar'); Then, in my parent theme, where I register the default sidebars available to any child theme, I'd like to use: if(current_theme_supports('header-sidebar')){ /* create a sidebar for the header area */ register_sidebar(...) }
You have to register the sidebars in the parent theme just late later enough. Use a hook that runs later, and child themes can register their theme support. ### Child theme add_action( 'after_setup_theme', 'register_header_sidebar_support' ); function register_header_sidebar_support() { return add_theme_support( 'header-sidebar' ); } ### Parent theme add_action( 'wp_loaded', 'register_theme_sidebars' ); function register_theme_sidebars() { if ( current_theme_supports( 'header-sidebar' ) ) register_sidebar( array ( 'name' => __( 'Header', 'parent_theme_textdomain' ) ) ); }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "theme development, add theme support" }
Set the default category of an attachment I wanted to apply the same categories that exist for posts to attachments, so I wrote this code: function wpmediacategory_init() { register_taxonomy_for_object_type( 'category', 'attachment' ); } add_action( 'init', 'wpmediacategory_init' ); The problem I am having now is that behaviour is not quite like with posts. There a 2 features I would like to achieve: 1. When adding a new attachment, set it to "Uncategorized" 2. When updating an attachment, if it has no categories selected, set it to the "Uncategorized" category. I have been trying to think what hooks I could be using, but without much success. How could I solve this problem?
To solve the problem 1, you could hook to add_attachment and edit_attachment hook. add_action('add_attachment', 'wpse_set_attachment_category'); add_action('edit_attachment', 'wpse_set_attachment_category'); function wpse_set_attachment_category( $post_ID ) { // if attachment already have categories, stop here if( wp_get_object_terms( $post_ID, 'category' ) ) return; // no, then get the default one $post_category = array( get_option('default_category') ); // then set category if default category is set on writting page if( $post_category ) wp_set_post_categories( $post_ID, $post_category ); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "categories, hooks, attachments" }
Adding multiple real estate properties to back end Client has a property management site. He wants clients to signup and enter rental each property into the system, with photos as well. These properties entries will not be accessible to public, but only to the user himself and the PM "admins". I could create a custom content type, that would be pretty easy I suppose. * How would I make them unpublished by default? * How would I create Prop mgmt specific admins, who would be able edit listings as well, but not have access to any of the pages or posts or any other admin related things? Thanks for any assistance.
You could assign them different roles and capabilities using the native settings in WordPress like Contributor which only allows them to write and manage their own posts but cannot publish posts.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types" }
Separating search results collectively by type My search results are limited to post types `book` and `author`. The following code in `search.php` displays all `author` posts first, then all `book` posts (I asked why post types are separated like that, but got no answer so far): while(have_posts()) : the_post(); if ( 'book-author' == get_post_type() ) { ?> <h2>AUTHOR</h2> <?php the_title(); } elseif ( 'book' == get_post_type() ) { ?> <h2>BOOK</h2> <?php the_title(); } endwhile; However I want to display these search results in two columns entitled "BOOKS" and "AUTHORS", each in its own `div` element. This code doesn't allow that, so how can I achieve such division?
There's two options. The first and probably the easiest option is to run the query twice on the page in each place you want to use it. // Author Block while(have_posts()) : the_post(); if ( 'book-author' == get_post_type() ) { ?> <h2>AUTHOR</h2> <?php the_title(); } endwhile; rewind_posts(); // Book Block while(have_posts()) : the_post(); if ( 'book' == get_post_type() ) { ?> <h2>BOOK</h2> <?php the_title(); } endwhile; Note: I've used `rewind_posts()` after the first loop which resets the post counter. The second option would be either filter the query that WordPress executes or sorting the results once you have them, however for this solution you should be fine with the above code.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "search" }
Creating multiple pages I have a few pages and I'm trying to import subpages into each like this: wp_insert_post ( array( 'post_title' => $something, 'post_type' => 'page', 'post_author' => 1, 'post_status' => 'publish', 'post_parent' => array(17, 25, 27, 29) ) ); So the structure should looks like: first->imported_name second->imported_name ... But this doesn't work, it creates only 1 subpage. Should I copy that code 5 times for 5 pages?
`post_parent` must be a single number, not an array. Each post can have only one parent. If you want to insert posts for multiple parents, use something like this: foreach ( array(17, 25, 27, 29) as $parent ) { wp_insert_post ( array( 'post_title' => $something, 'post_type' => 'page', 'post_author' => 1, 'post_status' => 'publish', 'post_parent' => $parent ) ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages" }
Displaying number of search results for each post type Using the code below, my search returns results from two different CPTs. How can I display the number of results for each CPT before displaying results? function more_posts_per_search_page( $query ) { if ( !is_admin() && $query->is_main_query() ) { if ( $query->is_search ) { $query->set( array( 'posts_per_page' => 500, 'post_type' => array( 'author', 'book' ) ) ); } } } add_action( 'pre_get_posts','more_posts_per_search_page' );
First, your callback to `pre_get_posts` is wrong. That is not the way that `set` works. If you had debugging enabled, you'd see `Notices`. It should be: function more_posts_per_search_page( $query ) { if ( !is_admin() && $query->is_main_query() ) { if ( $query->is_search ) { $query->set('posts_per_page',500); $query->set('post_type',array( 'author', 'book')); } } } add_action( 'pre_get_posts','more_posts_per_search_page' ); Second, there is nothing built in that I am aware of that will return those numbers to you, but it isn't hard to do using a WordPress Core function and a PHP one. $types = wp_list_pluck($wp_query->posts,'post_type'); // var_dump($types); // debugging $types_count = array_count_values($types); var_dump($types_count); // your data That code should be placed in your theme's `search.php`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "search, pre get posts" }
Subdomain multisite gives 404 on sub sites I used a one click install to install wordpress and then converted it into a sub domain multisite. I have made the required changes to the wp-config and htaccess file. The main site example.com works absolutely fine. When I try to add another site, it shows that the site has been successfully added. But the address sub1.example.com shows a page that says no content here and sub1.example.com/wp-admin gives a 404 error.(These are both generic pages similar to what my server shows on any random subdomain) I do have a wildcard subdomain registered but its corresponding folder on the server seems to have no wordpress related files. What can I do to fix this? Also, when I create sub1.example.com in wordpress, should I also register this subdomain on my cpanel or does the wildcard take care of it? And if I should register it, should I do this before creating a site in wordpress or after? (I tried all 3 scenaorios but I still get the same problem)
WordPress can use subdomains only if they are linked to the same directory as the WordPress installation. ### Wrong - wp/ // WP installation - subdomains/ // wildcard subdomains ### Correct - wp/ // WP installation & wildcard subdomains
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "multisite, subdomains" }
PHP help get_template_directory + PHP include Sorry my PHP skills are lacking. I want to use a php include in WP but I'd like to get the file path with `<?php get_template_directory(); ?>` I can't figure out how that would look. My non WP file looks like this: <?php include 'inc/social.php'; ?> Basically I don't know how to string two PHP commands together `get_template_directory` \+ include.
`get_template_directory()` and `get_stylesheet_directory()` both pull form the `wp-content/themes` directory. The difference being that the former always pulls from the _parent_ theme directory. Neither take parameters, so you just concatenate the rest of the path to the string returned from the appropriate function. That is: include get_template_directory().'/inc/social.php'; If your file is not in your theme directory, you cannot use those functions. They are very specifically theme functions.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "php, include" }
How to hide something from custom home page with php code? I need help to get the issue resolved. I have a wordpress custom-made site and it is with a custom home page. The index page of the wordpress site is used for updates purpose(blog). I want to hide something and not displaying on the custom home page. When the time i use "is_home()", the thing on blogging page is hiding and the thing is hiding when the time i use "is_page()". What code should i use to make it hide only on custom home page? Thank you!
Try !is_front_page() Or is_front_page() But it depends on what the function is.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, customization, homepage" }
Can I add a widget to the <head> of my site? I need to add a small bit of JavaScript to the `<head>` section of my site (on every page). I thought Widgets would cover this but I am only able to add widgets to the sidebar and nowhere else. I've searched around a bit and one solution on Stack Overflow appears to be modifying the functions.php file in my theme. The problem I have with this is that I am using a standard WP theme (Twenty Twelve) so unless I am mistaken, any theme updates would overwrite my changes to the file. I'm sure I must be missing something simple... I don't really understand why widgets can only go in the sidebar. That's different to every other system I've used.
I took a closer look at the answer Mayeenul suggested, and with a combination of that and the top answer I got it to work. Seems like a custom plugin is the way to go, and much easier than I expected to implement. First I created a folder at inside `wp-content/plugins/sv-custom-head` (using my initials to avoid conflicts) then added one plugins.php file, with this content: <?php /* Plugin Name: SV Custom Head Description: Description Version: 1.0 Author: Author URI: Plugin URI: */ function sv_custom_head() { ?> <script> (my code) </script> <?php } add_action('wp_head', 'sv_custom_head');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "widgets, html" }
Passing conditional arrays to WP_Query() I've looked around at a few places and could not find an answer. I was wondering what the best way to create a WP_query from possibly empty variables were. I have about 16 of these $_GET variables. if( isset($_GET['promotion']) ){ $promotion = $_GET['promotion']; if($promotion == 'promotion'){ $promo = 1; } else if($promotion == 'regulier'){ $promo = 0; } } In some cases `$promo` might not be set. So how can I create a `meta_query` let's say with dependant on if `$promo` is set or not. 'meta_query' => array( array( 'key' => 'model-promotion', 'value' => $promotion ) ) If the `meta_query` is not set but present in my `WP_query()` the query breaks. Thanks for the help!
Just build the static part of the args array, then add the conditional variables, then pass the args array to `WP_Query()`: // Static args $custom_query_args = array( /* static args here */ ); // Conditional arg if ( 1 == $promo ) { $custom_query_args['meta_query'] = array( /* meta query array */ ); } // Instantiate query $custom_query = new WP_Query( $custom_query_args );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, meta query" }
edit formatting.php in a theme so it wont get overwritten There are some parts of wpautop I want to remove, but keep the rest. I found in wp-includes/formatting.php within the function wpautop: $pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace & $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks Lines 251 & 261 in my version. I want to delete these parts of the function, and deleting or // the lines works fine. But how can I remove these lines in a theme file so it wont be overwritten in an update? Can I do something in functions?
There are no hooks in `wpautop()`, at all. Given that this is possibly the most complained about function in the WordPress world, it is odd that there are none but there you go. What you will need to do is remove the filter: remove_filter( 'the_content', 'wpautop' ); remove_filter( 'the_excerpt', 'wpautop' ); Create a version that does what you want, and add that filter to the same hooks: add_filter( 'the_content', 'my_wpautop' ); add_filter( 'the_excerpt', 'my_wpautop' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "functions, formatting" }
Pulling current post/page data into header.php I want to pull some post/page specific data (author name, post ID, publish time, etc) into header.php to be used in meta tags. I am having trouble figuring out the most efficient way to do this. It is my understanding that I will need to create a loop within header.php to pull this data. How can I go about creating a loop for the current page/post if I don't yet know the ID?
Main query is actually processed before template is loaded, so data is available in header (if a little less convenient to use). You don't actually _need_ loop, `get_the_ID()` should give you ID for the queried object and _most_ template tags have version that will return you results for that specific ID. Loop would work just as well, but it's not very common to run it this early.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "loop" }
How to find a callback attached to a bbpress hook? bbpress has a large number of callbacks attached to various hooks. I am familiar with this feature at the wordpress level but I am unable to locate where bbpress registers a large number of these callbacks. Specifically I would like to change the behaviour of the callback which is triggered via: do_action( 'bbp_template_before_forums_loop' ); If someone could help me locate this callback so that I can change the HTML it outputs that would be greatly appreciated.
To find an attached callback, you normally can just do the following: printf( '<pre>%s</pre>', var_export( $GLOBALS['wp_filter']['hook_name'], TRUE ) ); This should give you back an array of callbacks attached to a hook, ordered by priority (which serves as key).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "hooks, bbpress" }
How to create shortcode of this PHP code I tried a lot but failed to create shortcode of this PHP snippet: <ul> <?php $my_query = new WP_Query('post_status=future&order=DESC&showposts=10'); if ($my_query->have_posts()) { while ($my_query->have_posts()) : $my_query->the_post(); $do_not_duplicate = $post->ID; ?> <li><?php the_title(); ?></li> <?php endwhile; } ?> </ul> Can you tell me how to do that & also explain how to put PHP codes into shortcodes. Don't need to explain the basic as I know how to create a shortcode.
This should do it.. function future_posts_function($atts){ extract(shortcode_atts(array( 'poststatus' => 'future', 'order' => 'DESC', 'showposts' => 10, ), $atts)); $return_string = '<ul>'; query_posts(array('post_status' => $poststatus, 'order' => $order, 'showposts' => $showposts)); if (have_posts()) : while (have_posts()) : the_post(); $return_string .= '<li>'.get_the_title().'</li>'; endwhile; endif; $return_string .= '</ul>'; wp_reset_query(); return $return_string; } add_shortcode('future_posts', 'future_posts_function');
stackexchange-wordpress
{ "answer_score": 0, "question_score": -3, "tags": "php, shortcode" }
How to add a new link to the default register form's footer links? I would like to add a custom link to the footer section of the register form. How can I do this? I am using the `login_footer` hook: add_action( 'login_footer',array($this, 'add_forum_menu'), 50, 2 ); function add_forum_menu() { //need code to append the new items on the menu ) ); !enter image description here
I was looking at the wp-login.php file and noticed that there's an action location : <?php do_action('login_footer'); ?> available... to use. So add_action('login_footer', 'my_addition_to_login_footer'); function my_addition_to_login_footer() { echo '<div style="text-align: center;"><a href="#">link</a></div>'; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": -1, "tags": "hooks, login, actions, wp login form" }
How to show more than 5 posts? I am running code that shows child categories, and all posts in the child categories. But if there are more than 5 posts in a category, only the 5 newest are shown. How can I show all, or at least set a number like 9 posts etc.? My code: <?php $args = array( 'child_of' => 1 ); $categories = get_categories( $args ); foreach ($categories as $category) { echo '<li><a>'.$category->name.'</a>'; echo '<ul>'; foreach (get_posts('cat='.$category->term_id) as $post) { setup_postdata( $post ); echo '<li><a href="'.get_permalink($post->ID).'">'.get_the_title().'</a></li>'; } echo '</ul></li>'; } ?>
I think you could use the `posts_per_page` argument in your `get_posts` query: $args = array( 'child_of' => 1 ); $categories = get_categories( $args ); foreach ($categories as $category) { echo '<li><a>'.$category->name.'</a>'; echo '<ul>'; $posts_args = array( 'posts_per_page' => 9, 'category' => $category->term_id ); foreach (get_posts($posts_args) as $post) { setup_postdata( $post ); echo '<li><a href="'.get_permalink($post->ID).'">'.get_the_title().'</a></li>'; } echo '</ul></li>'; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "query, get posts, categories" }
Get all children page ID's including parent by title So I am getting all the children ID's as well as the parent ID to show content only for that page and all its sub-pages. This is the following function I created, but was wondering if there is a better way to do it? function get_all_pages( $page_title ) { $page = get_page_by_title( $page_title ); $pages = get_pages( array( 'child_of' => $page->ID, 'sort_column' => 'post_date', 'sort_order' => 'desc' ) ); $array = array(); $array[] = array( 'ID' => $page->ID ); foreach( $pages as $page ){ $array[] = array( 'ID' => $page->ID ); } return $array; } $allpages = get_all_pages( 'Page Title' ); foreach( $allpages as $page ) { if( is_page( $page['ID'] ) ): // Show stuff only on these pages endif; }
You have done this the hard way. `WP_Query` can do most of the work for you. function get_all_pages($page_title) { $page = get_page_by_title($page_title); if (empty($page)) return array(); $children = new WP_Query( array( 'post_type' => 'page', 'post_parent' => $page->ID, 'fields' => 'ids' ) ); array_unshift($children->posts,"{$page->ID}"); return $children->posts; } $allpages = get_all_pages('Sample Page'); var_dump($allpages); It is late, and I am sleepy, but I think that duplicates your function with the exception that your code, unnecessarily to my mind, produces nested arrays. My code gives you a "flat" array.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "pages, conditional content" }
Make posts automatically from an Online XML file through wp cron job I want to import posts from a RSS feed using the WP Cron API. Here is the link to the XML Feed. I activated different Feed Aggregator wordpress plugin but it gives error. Problem: FeedWordPress encountered the following error when trying to retrieve this feed: A feed could not be found at This does not appear to be a valid RSS or Atom feed. If you think this is a temporary problem, you can still force FeedWordPress to add the subscription. FeedWordPress will not be able to find any syndicated posts until this problem is resolved. A guy told me to write a php code to update the values in MySQL and then call in WP. I have no clue with this.
I have figured a way. There is a WP ALLIMPORT plugin. Here is the link if anyone else need help Download wpallimport plugin
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp cron, xml" }
Wordpress theme showing blank page Something is wrong to my installed theme, because when I am clicking on _Visit Site_ than its showing blank page. No error and no content, no navigation nothing to display. There is link below :- <
Your theme is trying to retrieve data from Twitter and store it. It is failing to do so for whatever reason. Contact the author of the theme and have them fix it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, permalinks" }
Ignores post_type when no results I have a custom searchbox that only searches a particular custom post type. On the results page I have modified seacrh.php to display the results slightly differently. Mainly the title is different. <?php if ( 'wpdmpro' == get_post_type() ) : ?> <h1 class="title">Documents Search</h1> <?php else : ?> <h1 class="title">Search</h1> <?php endif ?> This works when there are some rsults, but fails on no results and displays the default title? Why is the confitional failing. the url of the results page shows that the post type is still relevant? Any idea?
Use `get_query_var( 'post_type' )` instead of `get_post_type()`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types" }
Why is wordpress permalink path wrong for single blog posts? I'm developing my site with MAMP and my homepage is at localhost:8888/wordpress When I click on the link to my blog page (home.php) the url looks like this: localhost:8888/wordpress/blog All good so far. However, when I click on a blog post from the home.php template the url looks like this: localhost:8888/wordpress/blogpostname How can I make it so it's localhost:8888/wordpress/blog/blogpostname ? When I changed my permalink settings to localhost:8888/wordpress/%category%/%postname%/ it still left out the /blog in the URL. Why is it doing that and how can I fix it?
add `/blog/` in your permalink settings: /blog/%category%/%postname%/ or /blog/%postname%/
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "permalinks" }
Custom post type using standard post categories results in 404 when viewing /cpt/category The CPT has been registered fine, with the name 'qna' and slug 'advice'. Viewing domain.com/advice correctly displays the archive-qna.php template. Viewing domain.com/advice/custom-post-title also works correctly and displays using single-qna.php. The problem comes when adding these custom posts to the standard post categories. In that instance when viewing domain.com/advice/category results in a 404. I think I may of found a work around, creating a qna post that matches each of the standard categories we're using, then using a conditional within single-qna.php. However is there another way to solve this?
They will be available at: domain.com/category/your-category/ This means that if view this URL you might also see posts (the built in WordPress ones) in there too as they too can have categories. If you don't want these 'qna' posts to be mixed in with the default posts then you should create a taxonomy and use that: i.e. `advice-categories` Your advice posts will then be available at: domain.com/advice-categories/your-advice-category/ You can specify your own slug too just like Custom post Types.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, permalinks" }
How to use the same code for multiple pages? The code below prevents a page (defined by its title) from being deleted. When I try to implement two occurrences of this code (one for each page I want to prevent from being deleted) I receive the white screen of death. How would I list more than one page by title and prevent both from being deleted? add_action( 'wp_trash_post', 'stop_deleting'); function stop_deleting($page){ $page = get_page_by_title( 'About' ); if ($page) die('You are not allowed to delete this page'); }
Please **show** us your actual code, and don't just describe what you implemented. In this particular case, it is vital to see **how** you tried to implement _two occurrences_ of the code. Anyway, from what I understand, the following function should do what you've asked for: add_action('wp_trash_post', 'wpse_136052_do_not_delete'); function wpse_136052_do_not_delete($id) { if (in_array(get_post($id), array( get_page_by_title('About'), get_page_by_title('Other Page'), get_page_by_title('Third Page'), ))) die('You are not allowed to delete this page'); } // function wpse_136052_do_not_delete
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "pages, wp admin" }
Cannot override hooks.php I building a child theme for 'Responsive Theme' from Cyberchimps. I would like to change one hook. So I guess I need hooks.php file in my child theme. So I copied it from the parent. I made the same hierarchy (I guess this is the right approach). wp-content/[my_child_theme]/core/includes/hooks.php Copying file to theme root didn't help. I also tried to just recreate this critical hook. I put the code in my child functions.php file, but It's also not working, because hooks happen after the theme stuff (just my asumtion). So the question is simple: how to override parent theme's hook.php file?
`hooks.php` is not a file that belongs to any native WordPress convention. While copying files from parent theme is often mentioned as a technique it _only_ applies to template files, which are part of template hierarchy (native or properly customized one). Your guess that this is issue of timing is probably accurate. It's a little counter-intuitive but child theme is loaded _before_ parent theme. So running code on child theme load is too early to affect anything that hadn't yet happened. You need to create a function that will run that code and find a good timing for it to be hooked to. `after_setup_theme` hook might fit, but really specifics completely depend on timing of what parent theme is doing.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "hooks" }
Where is the User's Admin Bar Preference stored? I want it to default to off for new users In the `profile.php` admin page there is a checkbox for the _Toolbar_ : **Show Toolbar when viewing site**. I can't seem to find where this option is stored in the database. I would have thought it would be in the `wp_usermeta` table ... but I don't see it. My goal is to set the default value of this to "off" for new users. Then, of course, they would have the option to turn it on if they wanted.
You can update the usermeta upon user registration. Try adding this to functions.php and then adding a new user: add_action('user_register', 'update_usermeta_bar', 10, 1); function update_usermeta_bar($user_id) { update_user_meta($user_id, 'show_admin_bar_front', "false"); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "admin" }
Change the properties of a custom post type after it's been registered? The specific use case is that I have a CPT added through a plugin, and I'd like it to be hierarchical, but the post type options are hardcoded into the plugin. Is it possible to change the properties of a custom post type after it's been added via `register_post_type`?
While it's possible to manipulate CPT data after registration it's not very "clean" and harder for some things. Specifically for hierarchical setting registration adds it to rewrite right away: if ( $args->hierarchical ) add_rewrite_tag( "%$post_type%", '(.+?)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&pagename=" ); else add_rewrite_tag( "%$post_type%", '([^/]+)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name=" ); So you'll have to redo this really carefully and make sure it survives flushing rewrite rules properly. Altogether it would be more robust to look into forking or extending that part of plugin in question and just register CPT like you need it to.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types" }
Rename Default Category (Uncategorized) Via a Function I'm looking for a function to rename the default 'Uncategorized' category. The reason I need this is because I'm running a WordPress multi-site largely used by users with little technical knowledge and only allows the one, default category for their blog.
I think `wp_update_term` should do the trick: wp_update_term(1, 'category', array( 'name' => 'A Real Category Name', 'slug' => 'real-category-name' ));
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "categories, functions" }
How can I prevent the post_modified column in wp_posts from being updated? On my site, I display each post's Last Updated date instead of its Published date in order to let visitors know how recent the post is. I'm currently developing a new theme, and some of the features I'm building will require me to make edits to almost every post's featured image and custom fields. I'd like to prevent the Last Updated date from being changed when I do these updates, as I'm not really updating the content. Any way to do this? My current idea is to simply change the names of the post_modified and post_modified_gmt while I do the update - will this break anything, since WordPress will be trying to update columns that technically don't exist?
Add the following to `functions.php` when you are meddling and remove it after, or comment it out: function no_mod_wpse_136092($data,$postarr){ if (empty($postarr['ID'])) return $data; $old = get_post($postarr['ID']); if (!empty($old)) { $data['post_modified'] = $old->post_modified; $data['post_modified_gmt'] = $old->post_modified_gmt; } return $data; } add_action('wp_insert_post_data','no_mod_wpse_136092',10,2);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post meta, date" }
wordpress function to change post status I'm running the YouTube Video Fetcher plugin at . It fetches videos using the youtube api and displays them on your website. Within the plugin script, there is the following sequence: if (empty($items)) {$ret .= " 'No new videos.'";} else foreach ( $items as $item ) : Is it possible to change the wordpress post status from published to draft if "No new videos" are found? I am thinking the solution is using the wp update post function and something along the lines of the following: <?php // Update post $my_post = array(); $my_post['ID'] = $id; $my_post['post_status'] = 'draft'; // Update the post into the database wp_update_post( $my_post ); ?>
I guess it should work . As long as `$id` is available things are easy. <?php if (empty($items)) { $ret .= " 'No new videos.'"; $postid = $post->ID; //Supply post-Id here $post->ID. wp_update_post(array( 'ID' => $postid, 'post_status' => 'draft' )); } else foreach ( $items as $item ) : ?> Give it a shot.
stackexchange-wordpress
{ "answer_score": 20, "question_score": 8, "tags": "plugins, post status, wp update post" }
How to echo excerpts with wp_list_pages? I've tried to echo excerpts in `wp_list_pages` with the code below. It works, but only for one of the child pages. How would I echo the excerpt and title for each child page? <?php $children = wp_list_pages('title_li=&depth=1&child_of='.$post->ID.'&echo=0'); if ($children) { ?> <h2> <?php echo $children; ?> <?php the_excerpt(); ?> </h2> <?php } ?>
If you want to make use of all the nifty filters for the title and excerpt/content (and why would you not want that?) you should loop through a custom query instead of using `get_pages` and the pages' plain contents: <?php $args = array( 'post_type' => 'page', 'post_status' => 'publish', 'posts_per_page' => -1, 'post_parent' => $post->ID, ); $query = new WP_Query($args); while ($query->have_posts()) { $query->the_post(); ?> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php the_excerpt(); } wp_reset_postdata(); ?>
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "pages, query, excerpt, wp list pages" }
Theme licensing and permission on changing content When using themes on a WordPress site, can I customize (I mean modify/change files) that makeup the theme? So as to remove a particular section on stock photo provided in the pages? I like certain themes, but most of them include a footer, header, or something somewhere with extra information I would not want displayed, i.e.) theme name/version, developer link, etc. Is it ok to remove those from displaying on the website?
Well, this is totally up to the theme, its author(s), and the licence that the theme should be accompanied by. WordPress itself is published under GPL(v2). A huge amount of themes and plugins is too. Or at least a _similar_ licence (e.g., MIT). But in every case: What counts is what the product is _shipped_ with.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "customization, themes, licensing" }
Are custom post types lost when the theme is changed? I am about to begin work on a custom WordPress theme and I want to know how careful I have to be about custom posts. Suppose I create a WordPress theme that registers several custom post types. To my understanding this happens upon activation of the theme. If I were to create several posts of this custom type and then change to a theme that does not have that custom post type would I have lost the posts completely? What if I changed to another theme that DID have the same custom post type (if that is possible) would they still exist? Further, what about these same issues in connection with custom taxonomy? If I change to a different theme that does not support the custom taxonomy will the taxonomy data from custom posts be lost (if they are even saved). Will the data for the custom taxonomy still exist?
You don't lose anything. All your custom posts, taxonomies, terms and their relationships are still in the database. Without having those registered, however, the data can't be accessed, as in the WordPress edit page or custom queries and the like.
stackexchange-wordpress
{ "answer_score": 9, "question_score": 8, "tags": "custom post types, custom taxonomy" }
Remove meta robots tag from wp_head I am in need to remove just this line `<meta name=robots content="noindex,follow"/>` from `wp_head` but can't find the right hook to use it with `remove_action()`. <meta name=robots content="noindex,follow"/> Basically what I want to achieve is to remove just this line from the header but just for the search page. So in this case I would use something similar to: if ( is_search() ) { remove_action('wp_head', 'whatever-the-action-name-is'); }
I got it, the output is controlled by the WordPress SEO plugin as this is enabled in the site, so I had to tiny hard code in the plugin file class-frontend.php Obviously, I don't like that much this dirty workaround but it works by now outputting that meta in the search page as I want. In the class-frontend.php plugin file I had to replace the line 552 by this if ( is_search() ) { $robots['follow'] = 'nofollow'; } else { $robots['follow'] = 'follow'; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 7, "tags": "search, actions, wp head" }
Change the URL of an image from wp_get_attachment_image_src I call a lot of images with `wp_get_attachment_image_src()` and would like to off load those images to a CDN. Is there a filter to grab the URL and change it?
No, not strictly. You can check the source and see that there is no hook that would let you alter the URL. You should also notice this interesting bit of code: 512 if ( $image = image_downsize($attachment_id, $size) ) 513 return $image; Follow the trail to here and you get this: 141 // plugins can use this to provide resize services 142 if ( $out = apply_filters( 'image_downsize', false, $id, $size ) ) 143 return $out; If you hook into `image_downsize`... add_filter( 'image_downsize', function ($f,$id,$size) { // your own downsize function }, 10,3 ); wp_get_attachment_image_src(4); ... you should be able to return any URL you want, but it means you will need to duplicate more or less the whole of `image_downsize()` with changes of course.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "images, cdn" }
Generated media have incorrect aspect ratio Uploaded an image via standard 'add new' dialog to the WordPress Media library. Here were the original Media Settings: * Thumbnail - 150x150 * Medium - 300x300 * Large - 1024x1024 I uploaded a 650x144 image. Resulting generated image sizes: * 150x144.jpg * 300x66.jpg * 336x144.jpg Only the medium image has the correct ratio. The other two images are basically a crop of the middle of the original image. I've tried deselecting the 'crop thumbnail' box next to the thumbnail. I've tried changing the height to 0. So far nothing has worked. What am I missing?
Under settings >> media, change the height attributes to `9999`, and untick `Crop thumbnail to exact dimensions (normally thumbnails are proportional)` under the thumbnail size if it is ticked. When you are done, download and install "Force Regenerate Thumbnails". This is actually better than "Regenerate Thumbnails" as it deletes all redundant image sizes.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "media, thumbnails, cropping" }
Any plugin/theme available which suits my requirement? !insighter I have this WordPress website up. As one can see I've displayed alternate red and blue bands (which are images) with text written on them. I had the bands (around 100) manually created on Photoshop fitting in different sentences on them which is very tedious and time consuming. Are there any themes/plugins available where this kind of structure is available where I have to only add texts? I've searched on the net but no luck so far. Thanks in advance!
I doubt you'll find any themes or plugins designed for that _exact_ purpose, but it wouldn't be hard to roll your own solution. For example, if you put your text in a post or page, with each "band" in it's own paragraph, you could add in some simple CSS to get the desired effect. p { padding: 50px; color: white; } p:nth-child(odd) { background: red; } p:nth-child(even) { background: blue; } Here's a sample JSFiddle: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "plugins, themes" }
Run two wordpress on the same domain **Edit** I have a productive wordpress site (example.com) and a test wordpress site (test.example.com). For the two sites, I've a productive and a test DB. Everytime when I'll access the settings for the test site (test.example.com/wp-admin), I'll be redirected to the productive site (the URL looks then like this: ` I already changed the DB of the test site in the `wp-config.php` file, but nothing changed. How can I change the test site to the test DB and making it independent from the productive one?
Ok, you have two db's here, which is how it must be. One for your production site and one for your test site. You will probably copy between db's from time to time. I do that a lot between my production site and my test site which is on my computer locally. There are a couple of ways to change URL's, and this will be an issue if you copy between db's. I personally use a plugin called "Velvet Blues Update URL's". you can download it here On your test site, as I believe that is where you have your problem, open the plugin. You will see two input field, "New URL" and "Old URL". Enter your production site's URL in the old field like this > < In the new field, add the URL of your test field, like this > < Now select all options under those two fields and click "Update URL's". After this, update your permalinks. Hope this is what you were looking for. This will also work vise versa if you need to do this for production site
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp admin, installation, subdomains, domain" }
Redirect current user to their most recent custom post Is there a way that, if a user tries to access a particular page, they are redirected to their most recent post (In a custom post type)? Or, if the user has no posts, redirect them to the homepage?
To get the permalink of a users most recent post (of custom post type) perform the following query: $latest = get_posts(array( 'author' => $current_user->ID, 'orderby' => 'date', 'post_type' => 'my_custom_post_type', 'order' => 'desc', 'numberposts' => 1, )); if( $latest ) { $url = get_permalink($latest[0]->ID); } else { // No posts } For the redirect part take a look at the function wp_redirect.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "users, redirect" }
Change Custom Post Type singular_name through function/filter I'm working on e-commerce site using woocommerce plugin. My client will be selling tickets online. woocommerce plugin creates custom post type "Product". I want to change this cpt singular_name to "Ticket" (just a cosmetic change) I'm ok with keeping cpt slug to "product" as it requires for other woocommerce functions? !cpt_product Is there any function/filter available in wordpress to alter custom post type singular_name through function/filter
When you look at the source of `register_post_type`, you'll see that it uses `get_post_type_labels()`. And this function has a filter: apply_filters( "post_type_labels_{$post_type}", $labels ); Better use that instead of messing with the actual arguments.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, filters" }
Wordpress import media error I have developed a theme and had to export all contents via the exporter. Now when i import them via the importer plugin the posts etc get imported but there is an error importing media. Could you please help me out? Here is a screenshot: ![](
Admittedly, this is a guess. 1. The exporter, in the versions I have used, does not save your files to a local disk. It creates an XML file with references to your images on a server somewhere. 2. When the importer reads the XML file, it will download from that server and upload to your new installation. If your images are not available-- not accessible for download-- the importer cannot access the server where the images are stored, you will get upload failures. I am guessing that that is what is happening. Perhaps, the old server is refusing connections, or DNS is preventing access, or the old site has been taken down. If it is a DNS problem, you should be able to solve it by editing the XML file to replace the domain name with the numeric server IP. Untested, but can't think of why that wouldn't work. If the site has been taken down, I hope you have backups of the images somewhere.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, theme development, media, import" }
301 redirect from old URL structur to new I recently updated the permalink structure of a website from `/%postname%/` to `/%category%/%postname%/` this is obviously causing 404 errors. Instead of writing 301 redirects for each post is there any way to do this in a more automated fashion, within WordPress? I essentially want to programmatically 301 redirect the URIs from the old permalink structure to the new one.
You can make a catch on 404 in wordpress with filter 404_template Or you can use redirection plugin: < with Regex. Can you follow the link in this Question: Catch 404 after changing permalink structure from /%postname%/ to /%category%/%postname%/
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "redirect" }
Remove inline width from figure I add an image with caption to my page and need to increase `<figure>` width. But wordpress is adding an inline width. [caption id="attachment_44" align="alignnone" width="216"]<a href="image path"><img src="image path" alt="caption" width="216" height="95" class="size-full wp-image-44" /></a> caption [/caption] So, the DOM look like this: <figure id="attachment_43" aria-labelledby="figcaption_attachment_43" class="wp-caption alignnone" style="width: 216px"> <a href=""> <img src=" alt="Caption" width="216" height="95" class="size-full wp-image-43"> </a> <figcaption id="figcaption_attachment_43" class="wp-caption-text">Caption.</figcaption> </figure> I try to remove width="216" from code, but the caption desappear. How I remove this inline style?
**SOLVED** I'm using roots theme. So I open cleanup.php file and comment/remove this line: $attributes .= ' style="width: ' . (esc_attr($attr['width']) + 10) . 'px"';
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "posts, images, captions" }
Display and Update User Custom Meta via user-edit.php Is there a For/Loop available to display all the available WordPress User Custom Meta Data so that when on the user.edit.php screen you can see and update all custom metadata? I understand methods exist on a per item basis.
Two ways I can think of: 1. you could use a MySQL statement to get all usermeta matching an ID in the wp_usermeta table. That would get the custom meta as well, but it would also get other user settings that I don't think you want. 2. The other way is to define an array with all your custom data and loop through the array with a FOR loop. For example: $custom_meta = array("middle_name", "hair_color", "ear_size"); $userID = 1; for($i=0;$i<= count($custom_meta), $i++){ echo get_the_author_meta($custom_meta[$i], $userID); } I might be wrong, but I don't think there's a relationship in the WP db that defines whether a metadata is custom or not. So that's why you need to build the array beforehand.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "user meta" }
Adding class atribute to wp_nav_menu ul **Update:** this was caused by the fact that i didn't have a menu created in the menu page. I want to add a class to the ul of wp_nav_menu. I tried this code: <?php $defaults = array( 'menu_class' => 'menu', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', ); wp_nav_menu( $defaults ); ?> According to wordpress codex changing the _menu_ from 'menu_class' => ' _menu_ ', should change the class of the ul, but instead it changes the class of the div wrapping the ul. `<div class="this class is changed"><ul><li class="page_item page-item-2"><a href=" Page</a></li></ul></div>`
`menu_class` is indeed what changes the `ul` class. What's happening there is you didn't set which menu to use: * `wp-admin/nav-menus.php?action=locations`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus" }
Saving return value from the_author_posts_link() As you know, in the loop, `the_title()` function displays (echos) the post title to the screen, and `get_the_title()` returns it (so it can be saved in a variable). The same is true for the pair `get_the_post_thumbnail()` and `the_post_thumbnail()`. Now, what is equivallent to `the_author_posts_link()`? I need to save that information rather than displaying it.
The author posts link returns the author name which is linked to posts written by him. I think what you need is the author name of the post. It can be retrieved with `<?php echo get_the_author(); ?>` and if in case you need the link to the posts by this author then use: `<?php echo get_author_posts_url( get_the_author_meta( 'ID' ) ); ?>`. Please correct me if I am wrong!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "loop, author" }
After site transfer I'm still getting redirected to the old site (WordPress) I have transfered my WordPress theme on another domain doing these steps: 1. I have used a backup plugin and backed up database 2. Transfered wp-content folder to the new site 3. Uploaded the database to a new host 4. Changed `siteurl` in `wp-options` to a new one But I'm still getting redirected on the old URL pressing on the header. In `header.php` the PHP echo `home_url();` could be changed, so I'll be redirected on the new URL but I'm not sure that this is the solution. Would be glad to hear from you what have I done wrong.
I found the solution for this: > Settings » General » Change URL address I changed my site URL to new and it's working just fine.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "urls, migration" }
When does WordPress automatically enqueue jQuery? I understood that WordPress **ALWAYS** enqueues jQuery on all themes, thus it's reduntant to enqueue another jQuery with the same version. However, while developing a theme, for testing purposes I moved it to a subdomain (same domain, another WP installation, no content but the "Hello World" post). While the first enqueued normally the jQuery, the second stopped some functionalities and looking inside I've found that WordPress was not including jQuery automatically anymore. The question is: Does WordPress wait for something (don't know, maybe a minimum of widgets on widget areas, menus, etc) to call the script? To make sure, do I have to enqueue the native jQuery manually? I'm developing a theme with the purpose to sell it on Theme Forest and they only allow the native WP jQuery (no way to dequeue it and add from another resource). I'm using Wordpress 3.8
On the frontend, WordPress enqueues jQuery only when the admin bar is visible, usually only for users who are logged in. If you need jQuery, enqueue it. It will not be included twice in this case.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "jquery, wp enqueue script" }
Return the name of the post type I have this in the archive.php file of my theme: <?php else : ?> <h1 class="archive-title"><?php printf( __( get_post_type() ) ); ?></h1> <?php endif; ?> And it returns the slug for the post type. I'd like it to return the plural name of the post type instead. What should I use to replace get_post_type()?
Figured it out: <h1 class="archive-title"> <?php echo get_post_type_object( get_post_type() )->label; ?> </h1>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, archives, custom post type archives" }
woocommerce - products by category slug? good morning, I need to display the shop base page in a category layout,meaning first show all the products from category A and beneath it all the products from category B and so on.. I trying to use the built-in woocommerce shortcode -"products by category slug" but instead it displays products by products slug,what is the solution? here is the shortcode [product_category category="" per_page="12" columns="4" orderby="date" order="desc"] thank you
What @ChipBennett meant is to show the actual code that is represented by the shortcode, it can be found in the source. Take a look at this to see what's behind it - it is a `WP_Query`. Aside from that, the problem is - as far as I can tell - that you're misinterpreting what the shortcode does. Especially regarding the `orderby` parameter of `WP_Query`, which is **not** designed to order by category/taxonomy. It is just not part of core and > this is not something we want in Core. Here's a thorough explanation from Otto:1 Here on WPSE to be exact, as answer to Using wp_query is it possible to orderby taxonomy?.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, slug, woocommerce offtopic" }
Text editor has problem with having '<html>' in a post I'm trying to create a post on a WP 3.8 blog using the text editor that includes a `<pre>` tag with some JavaScript inside it. This JavaScript code happens to have a comment line that contains the string `<html>`. For some reason when I save a draft of the post, WP is adding `</html>` to the end of the code block right before the `</pre>`, right in the text editor. I have the Crayon syntax highlighter installed, but it shouldn't come into play while I'm editing the post. It's almost like WP sees an open `<html>` tag and is proactively trying to close it. I also tried escaping the angle brackets but the preview of the post showed the actual `&lt;` and `&gt;`. I even tried putting the `<html>` string inside a `<code>` block inside the `<pre>`, but the extra `</html>` was still added. Any idea why this is happening?
In the admin menu under Settings -> Writing, make sure the option to correct invalid XHTML is unchecked. Ref: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, post editor" }
linking to an svg through comments_popup_link I want to remove the text in the comment section and replace it with svg which falls back to png. This is my code so far <?php comments_popup_link('<object type="image/svg+xml" data="images/comment.svg"><img src="./images/comment.png"/></object>', '1 <object type="image/svg+xml" data="images/comment.svg"><img src="images/comment.png"/></object>', '%<object type="image/svg+xml" data="./images/comment.svg"><img src="images/comment.png"/></object>'); ?> I don't see anything wrong with my code plus my i have chmoded the images folder and its contents to 777, any pointers would be great. I am very new to Wordpress theme development so please excuse me if this is trivial. thanks
The problem is the relative URL. You have to be careful with relative URLs in WordPress. Relative URLs are interpretted by the _browser_ but the browser doesn't know about the URL rewriting that happens behind the scenes. Think about where your index file appears to be-- ` vs. where it actually is-- ` Similar problems occur with image locations. The apparent location-- the path relative to the displayed URL-- tends to be wrong. You need to provide an absolute URL for your image `src` using, probably, `get_template_directory_uri()` or `get_stylesheet_directory_uri()` as appropriate.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, comments" }
Short of raw SQL, can I query for multiple attachment metadata that have a given array key? With raw SQL through `$wpdb`, I believe that I could do something along the lines of this (untested): SELECT post_id, meta_value FROM postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE '%:"custom_key";a:%' That said, if there is built-in functionality for this kind of query then I would rather not reinvent the wheel. All of my codex digging has just returned ways to get the attachment metadata for a given id or set of ids, which will not do what I need. I could also retain a list of IDs with this particular array key, but I'd rather not keep this data since it seems like extra clutter...
While you can do this with `WP_Query`, I'd do this the way you are trying to avoid-- save a list in a separate key. The "pros" strongly outweigh the "cons" in my mind. 1. `LIKE` queries with wildcards, especially with leading wildcards, are not efficient-- aka, "slow" 2. and a `LIKE` query on serialized data is going to be prone to error 3. You will likely be running this query on display, which means that users see a delay Whereas... 1. The "space" needed to store another value in, say, the options table is negligible 2. And the query to retrieve the value is as about as efficient as a query can be 3. The work is pushed almost entirely to the backend, when the data is saved, so that any delay is seen by the administrators/authors of the site and not by the ordinary users. You can add and retrieve the data with the core functions `update_option` and `get_option`, the latter of which has caching mechanisms built in.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post meta, attachments, wpdb" }
Don't execute function on specific posts function content_strip_img($content) { global $post; if ($post->ID !== 1 || $post->ID !== 2 || $post->ID !== 3 ) { return preg_replace('/<img[^>]+./','', $content); } } add_filter('the_content', 'content_strip_img'); That doesn't seem to work? How do I exclude specific posts from a function - i.e. execute the function on all **other** posts?
This is a logic problem primarily, but your filter is faulty as well. Think carefully about that conditional. If any one of those values-- `$post->ID !== N`\-- is `true`, the whole thing is true, and as a post can only have one ID for any post two of those conditions will be true. It won't work the way you want. What you need is `&&`. It sounds strange, but think it through. The only way that can true is if the post ID is none of those values. Secondly, you should always (nearly always) `return` content from `the_content`. If you don't you effectly remove the post content. I have rewritten this code for you: function content_strip_img($content) { global $post; if ($post->ID !== 1 && $post->ID !== 2 && $post->ID !== 3 ) { $content = preg_replace('/<img[^>]+./','', $content); $content = 'Test'; } return $content; } add_filter('the_content', 'content_strip_img');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "exclude" }
Site Migration to WordPress: Handling Feeds I'm moving a site hosted with another blogging system to WordPress. This site's RSS feed is hosted at the URL I want to ensure that users with this RSS Feed in their feed readers continue to get updates when I move to WordPress. Is there a standard way in stock WordPress to handle this? If not, is there a standard plugin to handle this? If not, how **are** people handling this? Apache redirects? Something else?
I think it can be done with a redirection plugin. I won't recommend touching .htaccess file without expert knowledge. Add New Redirection like this: Source URL: /home?format=rss Target URL: Save the settings.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "rss, migration" }
Force buddypress groups to be private I want to give group creators no option to create public or hidden groups. All groups should be private. So that people still can see those groups but have to be invited or request a membership. The most simple method would be to hide the radio buttons(see pic attached). But I want to do it using a plugin or php. So, how can I force buddypress to make each group private?
In your theme or child theme, create an over-ride of this file: buddypress\bp-templates\bp-legacy\buddypress\groups\create.php Then adjust the form markup so that only the Private group radio button is created and it is checked. Creating theme over-rides: <
stackexchange-wordpress
{ "answer_score": -1, "question_score": -1, "tags": "buddypress" }
Create Custom Admin Fields I'm looking to create custom admin options/menu/fields (I'm not positive on the correct terminology) and would like some guidance. I found a post here which does speak about it in the answer: Tips for using WordPress as a CMS? I would like to create a field like the 'Attorneys' menu shown in @MikeSchinkel 's answer. If you know a page that has instructions on best practise to create this could you please link me? I have searched the net for hours on end for a solution and the best I came up with is the 'Custom Post Type UI' (< plugin which does not give me the flexibility I need. Thank you in advance!
Advanced Custom Fields and Pods are plugins that both deal with custom fields.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, wp admin" }
Filter meta request i've got a multisite where i query _specific custom post types_ from _one specific blog_. It looks like this: function unify_results_filter( $input ) { global $wpdb; $blog_id = get_current_blog_id(); $blog_source_id = '2'; $db_source_prefix = str_replace($blog_id, $blog_source_id, $wpdb->prefix); // if blog is not 2 and post_type is results, query blog id 2 if ( strpos($input, "post_type = 'results'") !== false ) $input = str_replace( $wpdb->posts, $db_source_prefix . 'posts', $input ); return $input; } add_filter( 'posts_request', 'unify_results_filter' ); Now this works for the posts themselves. However, i'd like to the _same for their meta values_. Is there a similar filter for meta request?
Why don't you use wp_query to retrieve posts. Its's easy to include meta values in wp_query and a safe way to retrieve posts from wordpress database. use this code to switch to the desired blog id and then after retrieving posts switch back to the original blog. <?php /* for global variables, since it is being changed or updated from time to time, please refer to Related Resources for more information */ global $switched; switch_to_blog(2); echo 'You switched from blog ' . $switched . ' to 2'; **//RUN WP_QUERY HERE** restore_current_blog(); echo 'You switched back.'; ?> References: Wp_query Codex Switch to Blog Codex
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, meta query" }
PHP in Wordpress? I'm stuck with a question. How far can I go with php with wordpress? If good it's of course not the same as using a server+db and a .php file to script everything you can imagine, but how far can I go with Wordpress? For example you have your standard while's etc. but then you have inserting, what if I want to insert something like this in a field in wordpress? Would this even be possible or something related to things like `substr`? $firstletter = $row['Name']; $firstletter2 = substr($firstletter, 0,1); $return .= '<li data letter="'.$firstletter2.'" >'; } return friendly ($firstletter2);
You can use everything that is available in PHP, as WordPress is a script depending on PHP. The only limitations you have are set by your version of PHP, and if you run huge scripts, your server configuration.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php" }
Undefined variable: row? I'm trying to select the `post_title` from `wp_posts` with a query which I did using this method: global $wpdb; $test = $wpdb->get_var( $wpdb->prepare(" SELECT post_title FROM {$wpdb->wp_posts}" ) ); echo "$test"; EDIT: It now gives me: Notice: Undefined property: wpdb::$wp_posts in /../../../../wp-includes/wp-db.php on line 566 Warning: Missing argument 2 for wpdb::prepare(), called in /../../../../wp-content/themes/pms72/page-home.php on line 73 and defined in /../../../../wp-includes/wp-db.php on line 992
First, it's not `$wpdb->wp_posts`, it's just `$wpdb->posts`. Second, you're using prepare() incorrectly. You use prepare when you have some variable data that you need to safely insert into the query string, not otherwise. Using prepare on a known string does nothing and throws a warning. For example: $data = 'example string' $query = $wpdb->prepare("SELECT post_title FROM {$wpdb->posts} where post_title = %s", $data); And then $query will be the SQL string that you're able to safely send to $wpdb->query. The string gets escaped, quoted, and inserted where that %s is. If you don't have any variable data that needs to be prepare'd for inserting into the query, then there's no point in calling prepare. For your case, since you're not putting any variables into the SQL, just skip the prepare. $test = $wpdb->get_var( "SELECT post_title FROM {$wpdb->posts}" );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, query, wpdb" }
Confusion about Site url and directory I have installed my wordpress in root/mysubfolder so my standard path is example1.com/mysubfolder (example1.com is the domain i have registered the webspace with) Now i want the wordpress installation to work with example2.com (registered another domain) Therefore i have set the redirect for example2.com to the folder mysubfolder in my webspace admin area what do i have to change to get this to work? i have tried this in the wp-config.php file: define('WP_HOME','http:example2.com'); define('WP_SITEURL','http:example2.com'); it works for the wp-admin and the homesite.. but if i click on a post the path is example2.com/post1 ..which doesn't work
i forgot to edit the .htacess in my folder... :) now everything works fine!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "urls, domain, site url" }
What is this format called (nested shortcodes)? When using plugins and commercial themes in WordPress, it's not uncommon to meet code like this: [one_half] [service_box] <h1>Title:</h1> <ul> <li>blah...</li> <li>blah...</li> <li>blah...</li> </ul> [/service_box] [/one_half] [one_half_last] Something more irrelevant here [/one_half_last] Does this thing have a name in the WordPress jargon?
I would use the phrase > Nested Shortcodes to describe it. You can find many questions using that phrase here on WPSE. The Codex also uses it, for example here: < Since the shortcodes in your example are related to the layout, we could perhaps call it: > Nested Layout Shortcodes to be more specific. If you have another phrase in mind, or a better suggestion, please share it with us.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "shortcode, wp editor" }
Bootstrap button menu on wordpress I have a simple 4 item menu on wordpress. I want to use the bootstrap button style for this menu. This is the hand-made code of what I want to get. <div class="menu-menu-container"> <ul id="menu-menu" class="btn-group"> <li id="menu-item-16" class="btn btn-default"><a href=" 1</a></li> <li id="menu-item-15" class="btn btn-default"><a href=" 2</a></li> <li id="menu-item-14" class="btn btn-default"><a href=" 3</a></li> <li id="menu-item-13" class="btn btn-default"><a href=" 4</a></li> </ul></div> I have no clue on how to tell wp_nav_menu() to build the menu in this way. I am working over twentythirteen as starting theme so I have to change the default menu to this style I want. I tried to use this guide but I wan't able to get the result I want. Does anyone have a solution for this?
The following should setup your menu with the correct classes and IDs applied to your container and ul. The codex entry for wp_nav_menu lists all the possible arguments. wp_nav_menu( array( 'theme_location' => 'primary', 'container_class' => 'menu-menu-container', 'menu_id' => 'menu-menu', 'menu_class' => 'btn-group' ) ); You can then add the required classes to the menu items by using the nav_menu_css_class filter. function my_special_nav_class( $classes, $item ) { $classes[] = 'btn btn-default'; return $classes; } add_filter( 'nav_menu_css_class', 'my_special_nav_class', 10, 2 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "menus, twitter bootstrap" }
How can I get the user that publishes a post? I have multiple users. Some are writers, others are editors. Is there a way to get the editor (id) that publish the post? I am able to get the author id but the not the editor's id that publish the article.
I am not sure if that is built in, but you can try adding something like this to your functions.php function set_publisher( $new_status, $old_status, $post ) { $publisher_id = get_current_user_id(); if ( $new_status == 'publish' && $publisher_id > 0) { update_post_meta($post->ID, 'post_publisher', $publisher_id); } } add_action( 'transition_post_status', 'set_publisher', 10, 3 ); And then when you want to get the publisher you use $publisher = get_user_by('id', get_post_meta(get_the_ID(), 'post_publisher', true));
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "actions, editor, publish" }
Edit box scrolls back to the top after updating post I've been quite annoyed by this. On post edit page, once I edited something in the middle of the page and hit Update, the whole page reloads and the edit box starts from the top again and I have to scroll-and-search my last edited point. Is there any workaround, solution to this?
I am not aware of clean native solution, however there have been at least one plugin in the past Save Editor Scroll Position (note - very outdated) trying to address this and might serve like prior art. There is also open trac ticket #18943 Scroll back to previous editor position after post save/update, however without patch suggestions or core developer feedback.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "editor, post editor, html editor" }
Is there os native application for wordpress? Is there os native application that makes possible to write and edit wordpress on a server? I'm thinking about something like a `Evernote`.
Here is a list of tons of Weblog Clients compatible with WordPress. Click Here If you're on Windows, I know alot of people liked Zoundry.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization" }
Website showing random code like texts in a post after pasting from MS Word My website is showing this type of content in a blog. When I click the title of same content, the content is fine there. It shows this type of content in one of the many listed contents. What can be the possible reason? Normal 0 false false false EN-AU X-NONE X-NONE DefSemiHidden="false" DefQFormat="false" DefPriority="99" LatentStyleCount="371"> UnhideWhenUsed="true" QFormat="true" Name="heading 2"/> UnhideWhenUsed="true" QFormat="true" Name="heading 3"/> UnhideWhenUsed="true" QFormat="true" Name="heading 4"/> UnhideWhenUsed="true" QFormat="true" Name="heading 5"/> UnhideWhenUsed="true" QFormat="true" Name="heading 6"/> UnhideWhenUsed="true" QFormat="true" Name="heading 7"/> UnhideWhenUsed="true" QFormat="true" Name="heading 8"/> UnhideWhenUsed=”true” QFormat=”true” Name=”heading…
I would guess that your problem is that you have pasted from MS Word. Go into your post and select "text" instead of "visual". Remove the markup. Alternatively, paste the article into Notepad, and then copy and paste back out of it into the visual editor.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "content" }
Thumb doubles the image file size My original images are 420x500/840x1000 and the file size varies around 15-30kb per image. Though when resized by wordpress/woocommerce into a thumb to 340x340(crop) the image size gets to 50kb+. The resizing happends automatically by Wordpress/woocommerce. Link to website \- I'm using XING, a theme from Themeforest. The image sizes has been changed in Woocommerce "Image Alternatives" to crop and 340x340px. function gpp_jpeg_quality_callback($arg) { return (int)100; } add_filter('jpeg_quality', 'gpp_jpeg_quality_callback'); Found this code in Functions.php though. Is this the issue?
What you need to do is to compress the image. Wordpress offers a filter to set the compression ratio. function my_jpg_compression($args) { return 75; } add_filter('jpeg_quality', 'my_jpg_compression'); > _**NOTE:_** What you are returning is the compression ratio. 70-80% is manageable and you will not notice much reduced image quality. Also, after applying this filter only future image's size can be reduced and not the one which are already uploaded. **What for already uploaded images?** You can use some awesome plugins to reduce image size and still keeping manageable quality. One of such a plugin is WP SmushIt. In fact you can use this plugin for future uploaded images too.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, woocommerce offtopic" }
Change template if tag selected I've got the following code, which changes the page template if 'street-style' is picked from the categories. However, I'd like to change this to the tag 'street'. I currently have: function get_custom_cat_template($single_template) { global $post; if ( in_category( 'street-style' )) { $single_template = dirname( __FILE__ ) . '/street-gallery.php'; } return $single_template; } add_filter( 'single_template', 'get_custom_cat_template' ) ; If I change `in_category` to `is_tag`, nothing happens. Is this not possible, or am I doing it incorrectly?
I think the function you are looking for is `has_tag()` or even more generically `has_term()`. Your function would then become: function get_custom_cat_template($single_template) { global $post; if ( has_tag( 'street' )) { $single_template = dirname( __FILE__ ) . '/street-gallery.php'; } return $single_template; } add_filter( 'single_template', 'get_custom_cat_template' ) ;
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "theme development" }
Forward an old url rewrite scheme to a new one? I have the following url rewrite for custom post type: add_rewrite_rule( 'event/([0-9]+)', 'index.php?post_type=event&p=$matches[1]', 'top' ); Due to a site structure change, I'll be moving this from `/event/id` to `/workshop/event/id` like below: add_rewrite_rule( 'workshop/event/([0-9]+)', 'index.php?post_type=event&p=$matches[1]', 'top' ); How do I return HTTP 301 on the original url scheme, from within a wordpress plugin?
An easy way to do this is to keep both your rewrite rules active (for now). On `single-event.php` you check for the URL, even before calling `wp_header()`. If the URL does not contain the base 'workshop', add a `wp_redirect()`: wp_redirect( get_permalink( get_the_ID() ) ); This way you should be all set. If you do not like the `wp_redirect()`, you can of course just modify the header information with PHP. I know this is not in the Plugin itself. If you really depend on the Plugin, you can do the same method by hooking into an early action.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, permalinks, url rewriting" }
Retrieve all posts within tag OR category? I've created a simple loop. And I have the following array for the query: $live_tags = array( 'tag' => 'live', 'showposts' => 5, 'post_type' => 'post', 'post_status' => 'publish', 'orderby' => 'date', 'order' => 'DESC' ); Where it says `'tag' => 'live'`, I need a logic that asks: if ('tag' == 'live' || 'category' == 'candy') But I am unsure how to do that within the WP_Query array. Anyone know how to retrieve posts from either tag, or category?
You need a `tax_query`. $live_tags = array( 'posts_per_page' => 5, // showposts has been deprecated for a long time 'post_type' => 'post', 'post_status' => 'publish', 'tax_query' => array( 'relation' => 'OR', array( 'taxonomy' => 'post_tag', 'field' => 'slug', 'terms' => 'live', ), array( 'taxonomy' => 'category', 'field' => 'slug', 'terms' => 'candy', ), ), 'orderby' => 'date', 'order' => 'DESC' ); $q = new WP_Query($live_tags); var_dump($q->request); Note that both the `{tax} (string)` and `showposts` arguments have been deprecated for quite some time. I would not recommend using them.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "categories, theme development, tags" }
What's the right way to share data between widgets? I've got a few custom widgets in my site, which I'm targeting to specific tags. There may be a case where there may be an overlap in widget targeting, and the desirable behaviour may be to only show the first of the widgets that match to that section or tag. Therefore, when a match occurs and the widget is to be displayed, I need to set a variable to indicate to the other widgets that are in that 'set' not to display anything. The obvious, but hacky, way to do this would be with a global variable, but this feels wrong. So I am hoping the Gods of Wordpress have a proper WP way to do it. Am I right?
Presumably, these are widgets that you are writing. If so, basic PHP class methods should do it-- set a static class property to hold your "overlap" data. class Foo extends WP_Widget { static $overlap; /*constructs etc*/ function __construct($id = 'twidg', $descr = 'Test Widget', $opts = array()) { $widget_opts = array(); parent::__construct($id,$descr,$widget_opts); /*do stuff*/ } function widget() { // set static::$overlap static::$overlap .= 'something-'; echo 'test widget :: '.static::$overlap; } } You could even create a "parent" widget to handle the "overlap" logic for all of your "child" widgets. For that see: * < * <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization, widgets, globals" }
using add_action without having custom plugin or theme I need to send an email after an author publishes or updates a post. But I don't like developing custom plugin or theme. Is there any plugin that runs a php script after publish. Or where can I insert my code and add have an add_action outside a plugin or theme?
There is no built in "user code" mechanism is WordPress. Your options for running your code are the theme's `functions.php` file, a plugin, or a mu-plugin. You are aware of the first two options, the first of which you reasonably want to avoid. Writing a simple plugin is pretty trivial so I would not be afraid to try that. The third option is less well known. If you create a directory called `mu-plugins` in the `wp-content` directory-- in other words, `/wp-content/mu-plugins/`\-- and place PHP files in there, WordPress will execute them automatically.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, publish, codex" }
Add capability for editors to modify custom fields Editors don't have a way to edit custom fields and I'm not seeing the capability in the WordPress codex. Is there a way to give access to that without making a user an admin?
You don't need a special capability. When editing a post the editor just need to click on the tab "option" in the upper right corner and check the box for visibility of custom fields.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, capabilities" }
How to remove p tags around img and iframe tags in the acf wysiwyg field I am querying an advanced custom fields wysiwyg field. Problem is in the output wordpress wraps occasional imgs and iframes with p tags no matter what i try. Deactivate the wpautop works `remove_filter ('acf_the_content', 'wpautop');`but if i try to exclude only imgs and iframes with the following snippet it fails: function filter_ptags_on_images($content) { $content = preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content); return preg_replace('/<p>\s*(<iframe .*>*.<\/iframe>)\s*<\/p>/iU', '\1', $content); } add_filter('the_content', 'filter_ptags_on_images'); Does anyone have a suggestion how to accomplish that goal? Best regards Ralf
Ok if you want to strip the p tags for img's and iframe's for advanced custom fields you have to exchange `the_content` with `acf_the_content` . The code looks that way: function filter_ptags_on_images($content) { $content = preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content); return preg_replace('/<p>\s*(<iframe .*>*.<\/iframe>)\s*<\/p>/iU', '\1', $content); } add_filter('acf_the_content', 'filter_ptags_on_images');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "images, wysiwyg, wp autop" }
How to implement WP_List_Table functionality for custom plugins (OR any substitution for wp_list_table plugin) for bulk action In the WordPress codex, following is highlighted in red for `WP List Table`. > "This class's access is marked as private. That means it is not intended for use by plugin and theme developers as it is subject to change without warning in any future WordPress release.". Is there any way to add bulk action and sorting functionalities like (`WP_List_Table` is doing) in custom plugins and how to use it?
For using the WP_List_Table functionality in a custom plugin, we can do one thing like below: 1. Copy the file class-wp-list-table.php to your plugin folder. 2. Then include that file in your plugin and extend the WP_List_Table (or else you can rename the class) class. 3. If we need any modification, we can do that from there. In this way,we can add bulk action and sorting functionalities like (WP_List_Table is doing) in custom plugins and so no need to test our plugin everytime a new WordPress version is released.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp list table, bulk" }
wp_trash_post function to only apply to posts, not pages! I have the following function that deducts at point when a post is removed. But when I remove a page, the wp_trash_post is also called. // Remove 1 point if their post get removed function deletePointFromUser($post_id) { $post = get_post($post_id); $authorid = $post->post_author; $currentQPointNumber = get_user_meta($authorid, 'points', true); // Delete 1 to the current Point Score update_user_meta($authorid, 'points', $currentQPointNumber-1); } add_action('wp_trash_post', 'deletePointFromUser'); Is there a way to restrict this function to only apply to posts and not pages?
You could just add something like: // Remove 1 point if their post get removed function deletePointFromUser($post_id) { $post = get_post($post_id); if( $post->post_type != 'post' ) return;//added code $authorid = $post->post_author; $currentQPointNumber = get_user_meta($authorid, 'points', true); // Delete 1 to the current Point Score update_user_meta($authorid, 'points', $currentQPointNumber-1); } add_action('wp_trash_post', 'deletePointFromUser'); Then your point subtraction will only occur if the `$post` is a post.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "functions" }
Continuous listing from a custom field I have posts with custom fields called "cb_vote_nb_vote" which holds the vote count for every post, what I want to do is let's say posts under A category will be listed based on vote count, I do that and show numbers with: query_posts('cat=47&meta_key=cb_vote_nb_vote&orderby=meta_value&order=DESC'); if(have_posts()) : while(have_posts()) : the_post() ; echo "<div id='listing'>"; echo $wp_query->current_post +1; echo "</div>"; ?> but the problem here is when you go to the new page it starts from number 1 obviously. How can I achieve that so the listing continues from the previous page?
First of all, please don't use `query_posts`, but a `new WP_Query`. Outpu count based on page is just a matter of a simple arithmetic operation using current page number and posts per page number. global $wp_query; $paged = $wp_query->get('paged') ? : 1; $posts_per_page = 10; // feel free to change this $args = array( 'cat' => 47, 'meta_key' => 'cb_vote_nb_vote', 'orderby' => 'meta_value', 'order' => 'DESC', 'paged' => $paged, 'posts_per_page' => $posts_per_page ); $query = new WP_Query( $args ); if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); $current_order = ( $query->current_post + 1 ) + ( $posts_per_page * ( $paged - 1) ); echo 'Current post order is :' . $current_order; endwhile; endif; wp_reset_postdata();
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, query, listing" }
Change the search icon in twenty fourteen I guess the title says all. I'm trying to change the search icon of the twenty fourteen theme, because I need a darker one. I tried like this: .search-toggle { background: url(' } which results in nothing.
This is more of a simple CSS question than actually related to WordPress. However, you need to change your `style.css`. As TwentyFourteen does not use images, but pseudo css-classes, you need to change this as well: .search-toggle { background: #fff url(' no-repeat; background-size: 30px; background-position: 10px; } .search-toggle:before { content: ""; } By the way, your background image is huge. Try providing a smaller one.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css, search, icon" }
Modify the WordPress admin bar CSS? I want to remove how it adds 32px to the top of the HTML tag. It's dumping it there with a STYLE tag right at the end with !important. It's damn impossible to override it, because there are no hooks or HTML and wordpress is setting it with like 5 css rules :/
What you are seeing is probably produced by `_admin_bar_bump_cb()`. From quick look at code it includes following instructions inline in `WP_Admin_Bar` class: > To remove the default padding styles from WordPress for the Toolbar, use the following code: > > `add_theme_support( 'admin-bar', array( 'callback' => '__return_false' ) )`;
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "admin bar" }
Using database in new instalation I have a Wordpress instance in my production environment. I have created a new raw instalation in my development machine, and I have imported the database from production. I have changed the wp_options table to make sure that the site_url and home are actually pointing to the named url I have in my local machine. However, when I access the site, it doesn't show up anything. What am I missing or need to do?
1. Enable debugging so that you can spot problems. 2. Alter the database connection information in `wp-config.php` // ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define( 'DB_NAME', 'database_name_here' ); /** MySQL database username */ define( 'DB_USER', 'username_here' ); /** MySQL database password */ define( 'DB_PASSWORD', 'password_here' ); /** MySQL hostname */ define( 'DB_HOST', 'localhost' ); 3. You can eliminate some issues by hard-coding a couple of web addresses also. If you are having a connection problem, I would recommend it. define( 'WP_SITEURL', ' ); define( 'WP_SITEURL', ' . $_SERVER['HTTP_HOST'] . '/path/to/wordpress' ); 4. Alter the embedded link URLs with a plugin like "Velvet Blues Update Urls" Additional work may need to be done depending on Item #1
stackexchange-wordpress
{ "answer_score": 1, "question_score": -4, "tags": "backup" }
How to remove title from category page in header I am trying to not show the page title on certain pages, including home, a custom post types page, and a category page (/category/blog). I came up with this, and it's working for everything but the blog page. if ( !is_front_page() && !is_post_type_archive('location') && !is_page_template('category-blog.php')) : <div class="page-title"> <div class="row"> <div class="col-sm-5 col-sm-offset-3"><h1><?php the_title(); ?></h1></div> </div><!-- /row --> </div><!-- /title --> endif;
Depends on what you want to do but most of the time to target blog page you will have to use : if( is_home() || is_front_page() ) I know this could be a little bit confusing but check this link. `!is_home()` might be the condition you're looking for.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories" }
Adding Alt Tag Column to Media Library List I'd like to add a column in the Media Library that shows that alt tag that way I can quickly add alt tags for all images that don't have one. How could I go about this?
Here's the code - function wpse_media_extra_column( $cols ) { $cols["alt"] = "ALT"; return $cols; } function wpse_media_extra_column_value( $column_name, $id ) { if( $column_name == 'alt' ) echo get_post_meta( $id, '_wp_attachment_image_alt', true); } add_filter( 'manage_media_columns', 'wpse_media_extra_column' ); add_action( 'manage_media_custom_column', 'wpse_media_extra_column_value', 10, 2 ); It could go to `functions.php` file or into your plugin.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "media library" }
disable publish button until condition is not met I currently wrote a plugins to customize my wordpress website. I surprisly find it easy to do many things with hook. Now I want to make author not be able to push publish button if no category is choosed ( I don't want uncategorized article and force author to choose something ) How I can did this with a little message telling to the user to choose a category when he try to click publish button if no category are checked. thanks
I finally found somethings. Not directly by cod it but I find a already wrote plugins for this. < Hope it's will help others wordpress user.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "hooks, publish, buttons" }
Disable Please visit the Update Network page to update all your sites. Notice from Dashboard I would like to hide below message you see on dashboard after a WordPress upgrade in Wordpress MU. I know for hiding version upgrade notice there is one filter as add_filter( 'pre_site_transient_update_core', create_function( '$a', "return null;" ) ); But I want to disable the following notice > "Thank you for Updating! Please visit the Update Network page to update all your sites." !enter image description here
This message was fired on two hooks. add_action( 'admin_notices', 'site_admin_notice' ); add_action( 'network_admin_notices', 'site_admin_notice' ); Remove this and you remove the message, use `remove_action`. To remove this function use a function, like the follow example. add_action( 'admin_menu','fb_hide_site_notice' ); function fb_hide_site_notice() { remove_action( 'admin_notices', 'site_admin_notice' ); } Now for the network ares: add_action( 'network_admin_menu', 'fb_hide_network_notice' ); function fb_hide_network_notice() { remove_action( 'network_admin_notices', 'site_admin_notice' ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite, wordpress version" }
meta_query compare='!=' with multiple custom fields a post has the following custom fields: 'my_custom_field' => 1 'my_custom_field' => 2 'my_custom_field' => 3 I now want to query all posts that do NOT contain the value 2 for 'my_custom_field'. I'm trying this: $args = Array('posts_per_page' => -1, 'post_type' => 'page', 'meta_query' => array( array( 'key' => 'my_custom_field', 'value' => 2, 'compare' => '!=' ) ) ); However, this is still returning my sample post, as my sample post has a field of 'my_custom_field' with a value other than 2 (1 and 3). I somehow need to change my query to say "Exclude posts that have at least one field of 'my_custom_field' with the value of 2". Can anyone help me? Thanks!
This might require writing custom sql with a subquery: $results = $wpdb->get_results(" SELECT * FROM $wpdb->posts WHERE ID NOT IN ( SELECT post_id FROM $wpdb->postmeta WHERE meta_key = 'my_custom_field' and meta_value = 2 ) "); then just iterate through the results as described here.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "meta query" }
Tab order of post admin page When I edit my post and update, I edit a textarea and hit a `Tab` key, then `Update` button will be activated and press `Enter` to admit the change. But in another environment if I press `tab`, then `preview` button is activated. Why is this difference of tab order happens? And which tab order is right?
Form fields have something called a tab index. So when you press the tab key it will know where to go next. However when a page has multiple forms the indexes can get mixed up, unless they are clearly specified in each field. Some wp form plugins give you the ability to add the form index range, that way if there are multiple form elements in one page they won't overlap. So to answer your question... the tab order will change from page to page depending on the form elements in it. Here's some more reading on tab index.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "admin menu" }
Global functions on WPMU I work in a multisite environment where all of the sites are related. A lot of recent developments have required me to copy and paste certain functions into many different theme folders, which causes problems if I need to update them everywhere. What would be the best way to have a global "functions.php" file? My thoughts are either to include a file in the themes folder and include it, or create a plugin and network enable the plugin.
What you are looking for is a "MU-Plugin"-- "Must-Use Plugin".. Originally these were called "Multi-User Plugins" and were intended for exactly your purpose-- to provide a way for site admins to enable functionality on all sites of an installation. Create a directory at `/wp-content/mu-plugins/` and put your PHP file(s) in it. WordPress will load the files automatically. MU-PLugins are "are automatically enabled on all sites in the installation" and cannot be deactivated except by physically removing the file. Be sure to read the "Caveats" part of the Codex page.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "functions, multisite, globals" }
Should I host support forum on wordpress.org or my own website? I have a Wordpress plugin WP Pipes hosted at < I see that it is convenience for users to ask question right in the support page at < but it will be a pain when we have lots of topics in there. Is there anyone here have experience about that? Should we offer support service right there in wordpress.org or host it in our own website? Any help would be appreciate. PS: I posted this question on stackoverflow but not has much answers for it.
All my support forums are on WordPress.org, but I do all my development on GitHub and that has led to a few support issues filtering in to the issues stream that are support issues and not bug reports. I also got a handful of people commenting on my blog for support, but I closed all the plugin-related blog posts. I disagree that a forum is necessarily better. I love digging through forums, but most users won't. I don't see why email is not manageable. In fact, some companies are using services like zendesk to handle support completely via email.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "plugins, support" }
wp-cron still running even though DISABLE_WP_CRON is true I have created a cron job to run wp-cron.php for me but I am seeing in my FPM logs where it's still running. From what I understand, is that with the cron job it wouldn't be hitting FPM to create any logs. Is there a way to trace this and figure out whats running the file?
If what you are seeing are hits to `/wp-cron.php`, there is nothing really that prevents a plugin or malicious bots from making a request to that file, with or without `DISABLE_WP_CRON` set to `true`, but with it set to `TRUE` the actual cron process should be killed.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "wp cron" }
WordPress WYSIWYG editor on demand, responsive I have created a WYSIWYG editor inside of a metabox, and I have loaded it on demand via javasacript. But the WYSIWYG is not responsive, like the default one is. How can I make it responsive? It sits inside of a table, and the table width is set to 100%. As the rows get smaller the WYSIWYG remains the same size but part of the editor becomes hidden. I've tried: .mceToolbarTop * { float:left; } .mceToolbarTop select { width:auto!important; } .mceToolbarTop option { float:none; } The html is really long, and difficult to format here. Or else i'd paste it. My container holding the WYSIWYG is 80% wide, and the WYSIWYG styles is set to 100%, so I don't know why its not respecting the styles I have set.
Using the following code to FORCE the buttons to wrap when the width of the editor hit a certain width, I used this code: where single-movie-row is the container holding my WYSIWYG .single-movie-row .mceToolbar td { display:table-row; float: left; } .single-movie-row .mceToolbar td:nth-of-type(11){ clear: left; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "tinymce" }
Display category description instead of "nothing found" page I'm using Wordpress 3.8.1 with the theme twenty fourteen. Unfortunately , when you click on a category with no post assigned to it for now , it displays a _not found_ page. I've tried to create a plugins with a hook that replace that by a text (like the description of the category). If there are no posts is in the category, only the description is displayed, if the category have posts, description is displayed and posts founds after. For now I don't find any ways to affect the _nothing found_ page. Is it possible to do this without modifying the category.php file (with plugin by hooks) like this thread
Make a child theme. Copy category.php into your child theme. Comment out lines 17, 33, 46, 48, and 50. The category checks if you have any posts under that category and if not shows 'Nothing Found'. You're essentially removing the if statement. This will show the category title if there are not posts under this category.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories, content, theme twenty fourteen" }
Hack nav menu to add gettext() to menu items? I'm translating my whole site with gettext and I'm using shortcodes for the content in my pages that in turn call gettext. However shortcodes don't seem to work for menu items I need to figure out a way to translate them. I'm wondering whether there is some way to modify my menu from my functions.php to add it a _("") function somewhere between retrieving the menu items labels from the database and echoing them. Is that possible? if not, how can I translate menu items?
Retrieved menu items pass through `wp_get_nav_menu_items` filter, as well as few others in `wp_get_nav_menu_items()` and around. \-- EDIT - This is what I used: function translate_menu( $items, $menu, $args ) { foreach ( $items as $key => $item ) { $items[$key]->title = _($items[$key]->title); } return $items; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "localization" }
Existing Ecommerce plugins with Custom Post Types I am developing a solution which is selling a service (can not be categorized as product) I have developed custom post types and taxonomies but I do not want to re-invent the wheel by adding payment gateways just for this purpose. Is there any way I can customize the "Product" post type in any existing ecommerce plugin available. Thanks for your support
You should download en use WooCommerce with buildin payment gateways You can add a product type with something like: function my_add_product_type( $types ) { return $types["service"] = "Service"; } add_filter( "product_type_selector", "my_add_product_type" );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin wp e commerce, woocommerce offtopic" }
What is the best way to revert to www version of domain name? My site uses a bare domain, example.com. I want to use Google's Page Speed Service, which requires a www subdomain, like this www.example.com Google says the server must use a 301 redirect. What is the best way to do this? Can I simply change the WP General Settings and add the www there?
You can change it at settings -> general, update Site address and wordpress address. With my site wordpress automatically redirects the domain to www.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "urls, options, site url, google" }
Why function hooked using object are executing at all time? I tried to use class and object in plugin. I made a simple function with a `shortcode` but it is executing the function without pasting the shortcode to any page/post. class example{ function ex_funct(){ ?> <h3>Hello</h3> <?php } } $obj = new example(); add_shortcode('examp_code',$obj->ex_funct()); Why it is showing Hello at admin as well front end header without pasting the code `examp_code` ? What is happening here?
That happens, because you _run_ the function in `add_shortcode()`. To send is as callback, use: add_shortcode('examp_code', array ( $obj, 'ex_funct' ) ); Now you have still a problem: you create output in your shortcode callback. Never do that, you have to return a string. Change it to: function ex_funct(){ return '<h3>Hello</h3>'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, plugin development, shortcode, oop" }