INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Use Tag input metabox style for Categories I am using Categories to create news timelines, For example < (check the cloud at the bottom of the page for more examples) The problem is in the Add Post screen. The Categories input metabox uses checkboxes. As the list of categories grows, scrolling through this list is becoming very timeconsuming. I could convert the Categories to Tags (which is very easy) so that I could use the Tag input metabox, which has an ajax autocomplete, but then I would have to change the theme code to throughout the site so that it would display tags instead of categories. So I was wondering if I could just change the Category Metabox to have the same Ajax autocomplete style as the Tags Metabox. All advice appreciated!
You can change the category metabox. You can create custom metabox as per your need which contains all categories in proper layout. Also you can search for plugins, say HTML5 category selector plugin <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "categories, metabox, tags" }
Convert all dates in field to Unix time, except those already in Unix time I have a meta field that is mixed with MM/dd/yy hh:mm dates and Unix timestamp dates. How do I convert all of the MM/dd/yy hh:mm dates in the db to Unix? I have only limited PHP and SQL knowledge so be gentle. Thanks!
**strtotime** is php function that can be used for this purpose. **strtotime** — Parse about any English textual datetime description into a Unix timestamp 1. Firstly get all the posts using meta key . 2. Then get date value from meta field. 3. Then convert to unix timestamp. 4. Then update again. $args = array( 'posts_per_page' => -1, 'meta_key' => 'meta_key_name' ); $myposts = get_posts( $args ); foreach ( $myposts as $post ) : setup_postdata( $post ); $date = get_post_meta(get_the_id(), 'meta_key_name', true); if( strtotime($date) != false ){ // To exclude dates which are already in timestamp update_post_meta(get_the_id(), 'meta_key_name', strtotime($date)); } endforeach; wp_reset_postdata();?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, sql, timestamp" }
Loading shortcode stylesheet only when shortcode is in text widget I would like to load shortcode stylesheet only when it will be put in text widget. Please help somebody.
I think you should be able to register your stylesheet with `wp_register_style()`, then load the stylesheet via `wp_enqueue_style()` from within the shortcode's function, so it only loads when the shortcode is executed. For a rundown on how this will work here's a good article. It refers to scripts, but I believe the same is true for styles: < (Also, if you need shortcodes to run in text widgets be sure to add this to your plugin or functions.php file: `add_filter('widget_text', 'do_shortcode');`)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode, css, widget text" }
What does the term "bundled-theme" mean? I have occasionally heard the term "bundled-theme". I know what a WordPress theme is, but I don't know what a "bundled-theme" is. I came across that term recently when reviewing the WordPress documentation: > "...For core (and bundled themes), this is always WordPress."(<
The term bundled theme is simply just a name/term used for the default (twenty-something) themes shipped with wordpress. The current version of wordpress 3.9.1 have three of themes shipped by default, namely 'twentytwelve', 'twentythirteen' and 'twentyfourteen'. The two previous twenty-something themes namely 'twentyten' and 'twentyeleven' are also available for download and is still currently been supported by the wordpress team
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "themes" }
Change Twenty Twelve's comment form in a child theme I have a custom child theme of Twenty Twelve. I want to change the text "Leave a reply" to "Leave a comment", and also remove the website field from the comments form. How can I do this? Thanks.
You can use filters in custom functions to modify the default output of the comments form via your child themes functions file. **Modify the comment form "Leave a reply" text.** add_filter( 'comment_form_defaults', 'wpsites_modify_comment_form_title' ); function wpsites_modify_comment_form_title( $defaults ) { $defaults['title_reply'] = __( 'Leave a Comment' ); return $defaults; } **Remove The Website URL Field From Comment Form** add_filter('comment_form_default_fields', 'wpsites_remove_website_url_field'); function wpsites_remove_website_url_field($fields) { if(isset($fields['url'])) unset($fields['url']); return $fields; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "child theme, comment form, theme twenty twelve" }
Create a custom URL for blog archive I'm playing around with a test site and I've set up a static page as home page. Now I want to make a menu item called `Blog` \- with url `example.com/blog/` \- where I'll list the latest articles. I made a custom page template and changed the `WP_Query` so that it queries a list of 10 latest posts. I then created a page and set the permalink to `example.com/blog/`. For the permalinks, I'm using a custom structure `/blog/%postname%/` so that my blog posts are like `example.com/blog/post-name`. The issue: I would also want that the monthly archive page and the category list page also use that custom page I made instead of their respective template files. Or another solution I was thinking about is to get the normal archive page to work without using the custom page pointing to `example.com/blog`. I'm kinda confused about how to implement the solution.
When you set up a static page as home page, you can set up also a page for the blog archive. If you do that, you don't need to alter the WP_Query in the blog page template, you only need to work with The loop like in a archive template file. When the page for the blog archive is requested, Wordpress will make the correct query for the blog archive. To make the monthly/category archive use a different template file than the standard, you can use the template_include filter and the functions is_category() and is_date(): add_filter( 'template_include', 'inlcude_archive_page_template' ); function inlcude_archive_page_template( $template ) { if ( is_category() || is_date() ) { $new_template = locate_template( array( 'the-archive-page-template.php' ) ); if ( '' != $new_template ) { return $new_template ; } } return $template; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "archives" }
value of metadata is null wrong use of if statement I'm using the WP-Ratings plugin which uses the Wordpress built in custom fields to save values of ratings. The name of the custom field is `ratings_score`. I want to ask if each post has a specific rating. What I'm doing is inside the loop doing following: <?php $rating = get_post_meta($post->ID, 'ratings_score', false); ?> <?php if ( $rating == 2 ) ) { ?> <script> console.log("test"); </script> <?php } ?> But it does not work. Am I doing it wrong? I also tried to ask `if ( $rating == '2' )` but thats the same issue. There are definately posts which have `2` as value of `ratings_score`
Try: $rating = get_post_meta($post->ID, 'ratings_score', false); var_dump($rating); You will notice that you get an `array`, even if your `ratings_score` is `2`. To wit: array(1) { [0]=> string(1) "2" } That will never equal `2` so your condition will never work. The third parameter of `get_post_meta()` if set to `true` will collapse that array to a scalar, and that will work. $rating = get_post_meta($post->ID, 'ratings_score', true); var_dump($rating); Note that if your post has multiple `ratings_scores` you will only get one of them and it may not be the one you want. To make this work with multiple `ratings_score` entries use: $rating = get_post_meta($post->ID, 'ratings_score', false); if (in_array(2,$rating)) { echo 'found it'; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "loop, post meta" }
How to customize custom taxonomy url? I have a Custom Post type "Data" with a custom Taxonomy "data-category". Currently my site url when I visit a 'data-category' shows like this : www.mysite.com/data-category/home-loan Here **Home-Loan** is a child of **Personal Loan** data-category. I need my url to show like this : www.mysite.com/personal-loan/home-loan Yes I need to get rid of 'data-category' from my url. Thanks
Found the solution. By default wordpress doesn't show hierarchical URL for custom taxonomies. Therefore while registering custom taxonomy, we must include the rewrite variable. $args = array( 'rewrite' => array( 'hierarchical' => true ), );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom taxonomy, permalinks, urls" }
How to know which wordpress plugin is exporting site information to plugin author? Is there any plugin or method to know outgoing data? Nowadays every 5th plugin use to fetch data from sites. And I noticed that plugin authors are very enjoying this function. But as plugin users I'm liking it sometimes. So far I've been digging into plugin files to remove their codes. But its not possible to do after every plugin update. I think this features is facilitated by wordpress own functions. Is there any method to turn it off? **Edit:** For example Yoast seo plugin uses this file to fetch information about users. He even gets contents from database queries. Isn't it too much? The same way any plugin can get passwords too.
The functionality of making network requests for getting and sending data is abstracted into HTTP API in WordPress. As long as plugins do use related functions (and not make requests directly via raw PHP) you have degree of control over the behavior. The easiest way is probably to only whitelist hosts you need/trust and leave rest blocked. define( 'WP_HTTP_BLOCK_EXTERNAL', true ); define( 'WP_ACCESSIBLE_HOSTS', 'api.wordpress.org,*.github.com' ); See Block External URL Requests in Codex.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins" }
Create dynamic wordrpess blank page I've created a submenu in wordpress using add_submenu_page: add_submenu_page(null,'Page Title','Page Title','administrator','page-slug','page-callback'); I want to create another page like this with the condition that the page will be totally blank without creating a new file does wordpress have a function like this?I want it because I want to generate and download an xml file there and if the page has headers and footers the page downloads them too.Any Sugestion? Thank You.
Try something like this: in the load hook, you can ouput your xml code. u function my_menu_pages() { $hook = add_submenu_page( null, 'Page Title', 'Page Title', 'administrator', 'sub-menu-slug', function() { } ); add_action('load-' . $hook, function() { // add your xml code here, // you will get a blank page to start with exit; }); } add_action('admin_menu', 'my_menu_pages');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "admin menu, add submenu page" }
A question about add_action() I was following this ( < ) tut on codex. The part where a class is created and is called in add_action. No argument was passed to `emailer::send` ? Why? It was required in the function definition.
The `emailer::send` is the function callback for a `publish_post` action hook. This action hook accepts only one parameter which is the post ID and it is passed by Wordpress. When you define an action hook, you set what parameters are passed to the callback functions. For example: $arg_1 = "The aregument value"; do_action( 'my_custom_action', $arg_1 ); Every time you hook into `my_custom_action`, the `$arg_1` value is passed to the function callback automatically. add_action( 'my_custom_action', 'my_custom_action_callback' ); function my_custom_action_callback( $arg_1 ) { //Do whatever } In the example you are talking about, the `publish_post` action hook is is used. This action hook accept one argument, the post ID, and this argumente is passed to `emailer:send` automatically by Wordpress.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development, actions, oop" }
unregister_sidebar() in stand-alone theme not working With this StackOverflow Q&A I can't make the `unregister_sidebar()` work for me. ### Scenario I have developed a theme using a sidebar area, where I've used a Widget. But I don't want the 'Editor' to get access to this Sidebar Widgetized Area in Admin area. So I want to do a tweak in my theme's `functions.php`, where I previously declared `register_sidebar()` somewhere to register the sidebar. I understood that, setting a less priority will trigger the unregister function more earlier, so I tried with: function site_unregister_sidebar() { if ( is_admin() && current_user_can('editor') ) { unregister_sidebar( 'my_custom_widget_area' ); } } add_action('widgets_init', 'site_unregister_sidebar', 1); But nothing is happening. * What actually I'm doing wrong? * Is there any other way I can achieve this?
Thanks to Milo and G.M. for pointing to the master key, as G.M. said: > _you have to use a lower priority than one register_sidebar runs, but lower priority means higher number._ So the final code that is working: function site_unregister_sidebar() { if ( is_admin() && current_user_can('editor') ) { unregister_sidebar( 'my_custom_widget_area' ); } } add_action('widgets_init', 'site_unregister_sidebar', 20); Because I set my sidebar with priority of 10 with the **same hook** \- `widgets_init`. function theme_widgets_init() { register_sidebar( array ( 'name' => 'Custom Widget Area', 'id' => 'my_custom_widget_area' ) ); } add_action( 'widgets_init', 'theme_widgets_init', 10 );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "sidebar, editor, register sidebar" }
User submitted post I'm sure there are plugins to do this but I wanted to try and do it myself. I have a form that contains a title and a content/message area. I would like to add this form as a post when fill it in. How do I go about adding the user completed form as a post. Any tutorials or pointers would be greatly appreciated.
You can create your form, submit it to `PHP_SELF`, sanatize your data and finally run your data through `wp_insert_post() Function`. You should be able to research everything else to achieve what you're looking for but this will get you started. Good luck!
stackexchange-wordpress
{ "answer_score": 1, "question_score": -3, "tags": "posts, users" }
Sorting get_post_ancestors array I have written this code for my breadcrumbs (i'll give only the part that I have problem with): } elseif (is_page()) { if($post->post_parent){ $anc = get_post_ancestors( $post->ID ); foreach ( $anc as $ancestor ) { $output = '<li><a href="'.get_permalink($ancestor).'" title="'.get_the_title($ancestor).'">'.get_the_title($ancestor).'</a></li><li><i class="fa fa-angle-right"></i></li>'; echo $output; } So for a page I'm getting the array of ancestors and it works fine if I have single ancestor. When I have two of them or more then (by default as the codex states): `The direct parent is returned as the first value in the array. The highest level ancestor is returned as the last value in the array.` And that echoes out `HOME > PARENT 2 > PARENT 1 > PAGE TITLE` How can I sort the $anc array so I could reverse it?
OK Thought I need some special WP func to do it and as it turns out the simple answer is the best. krsort($anc);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "sort" }
Get URL of current post but not the page number Instead of using a plugin, I am manually adding buttons into my template file, like so: <div class="fb-like" data-href="<?php get_permalink() ?>" data-width="100" data-layout="button_count" data-show-faces="false" data-send="false"></div> However, when I have a multipage post, I don't want that the like button links to `/the/post/2` on the second page, but to `/the/post` (i.e. the first page). I have been looking through the docs but there doesn't seem to be a way to get permalink of the post, without the page number. Can anyone help?
I don't think your code works as expected because you are not printing the URL of the post. Note that `get_permalink()` returns the permalink of current post inside a loop but doesn't print it like `the_permalink()`. So, you should use `<?php echo get_permalink(); ?>` or `<?php the_permalink(); ?>`.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "templates, pagination" }
LogOut button only if logged in in front end menu widget I would like to add a "LogOut" button at the end of my sidemenu - but of course only, if someone is logged in. I also want to have it in two languages using qtranslate. At the moment I have created a new Menu Item "Log Out" with a link to `/wp-login.php?action=logout` which works, but always shows up of course. Is there a way to put something like this in the function? Any help - or just a hint would be very nice! :)
To add a menu item to the end of a nav menu you can use the `wp_nav_menu_items` hook. Combine that with `is_user_logged_in()` and you ought to have it. function add_last_nav_item($items) { if (!is_user_logged_in()) { return $items .= 'your login link'; } } add_filter('wp_nav_menu_items','add_last_nav_item'); As far as translation, I assume that qTranslate uses the standard translation functions, but I'm not sure as I don't use it and as it is a third party plugin that part of the puzzle is off-topic anyway.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "logout" }
get_terms Parent Tags I'm using a function that I think it uses this code to get the tags from a taxonomy: if($taxonomy){ $tags = get_terms( $taxonomy, 'order=ASC&hide_empty='.$show_empty.''); As it is, is extracts all the tags(parent & child) from that taxonomy. But what I need is to extract only the parent or child tags from a specific `tag_ID(14)`. I've tried to include `child_of=14` and `parent=0` but couldn't make it. Could you give a advice?
The `parent` argument should do what you are asking. > > **parent** > (integer) Get direct children of this term (only terms whose explicit parent is this value). If 0 is passed, only top-level terms are returned. Default is an empty string. > > < That is `parent=14` should get all of the immediate children of term 14, but no grandchildren or great-grandchildren. If that is not working I have to assume that a plugin or something in your theme is interfering, or I have completely misunderstood your problem.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "terms" }
Call to a member function add_rule() on a non-object I want the page mysite.com/product to be accessed with the URL > mysite.com/product/productname instead of mysite.com/product?name=productname I am trying to achieve this with the code in the plugins main file: add_rewrite_rule('^(product)/([^/]*)/?', 'product?name=$matches[1]','top'); but I am getting the error: > Fatal error: Call to a member function add_rule() on a non-object in /location/wp-includes/rewrite.php on line 21 Any suggestions?
You're calling it too early. Call it on the init hook or later, e.g.: add_action( 'init', 'add_alexes_rules' ); function add_alexes_rules() { add_rewrite_rule('^(product)/([^/]*)/?', 'product?name=$matches[1]','top'); }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "permalinks, url rewriting, rewrite rules" }
ACF checkbox array is returning numbers, not labels I am using Advanced Custom Fields and the add-on Repeater to create a field in the admin through which a user can select multiple icons. Each icon has an associated label, and I'm trying to return the results of the checked icons in a `foreach` loop. Here's my code: <?php // icons foreach (get_sub_field('nav_widget_platforms') as $label => $value) { echo '<div class="mps-nav-context"><i class="icon-'.$value.'" title="'.$label.'"></i><span>'.$label.'</span></div>'; } ?> So for example, if the checkbox `cloud : eCommerce` is selected, the `$value` should be `cloud`, and the `$label` should be `eCommerce`. The problem is that `$label` is returning numbers, not labels, so that the page is displaying `0`, `1`, etc. depending on which order it is in the array. I'm not sure what I'm doing wrong here, or how to troubleshoot it.
ACF is actually doing what it should - storing a numerical array of selected values. If you want the label you can levy `get_field_object`, which returns information about the custom field (rather than the value of it for the given post). $field_obj = get_field_object( 'nav_widget_platforms' ); $platforms = get_field( 'nav_widget_platforms' ); foreach ( $platforms as $platform ){ echo $field_obj['choices'][ $platform ] . ": $platform<br />"; } <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "advanced custom fields, array, php" }
Why this plugin is not working? I am testing jQuery in my wordpress plugin. Two files 1. main_plugin.php 2. js_plugin.js (Both in the same directory HelloWorld). CODE: PHP FILE: <?php /* Plugin Name: jQuery Test Plugin Plugin URI: Description: This plugin is a test Author: Rana Faiz Ahmed Author URI: */ function load_my_script() { wp_enqueue_script( 'script-name', WP_PLUGIN_URL . 'HelloWorld/js_plugin.js', array("jquery"), false, true ); } add_action( 'wp_enqueue_scripts', 'load_my_script' ); JS file: jQuery('.entry-header').click(function(e) { e.preventDefault(); jQuery(this).remove(); });
`WP_PLUGIN_URL` doesn't have a trailing slash, so your script tag is likely trying to load a file from the wrong location. That said, **don't use`WP_PLUGIN_URL`**, use `plugins_url()` instead. plugins_url( '/HelloWorld/js_plugin.js' )
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, plugin development, jquery, javascript" }
add_rewrite_rule not registering on Multisite I have a multisite install of WordPress. I have installed the plugin Monkeyman Rewrite Analyzer so I can see all the rules I have registered. The code below is how I am registering the rule: add_action( 'init', 'add_init_rules' ); function add_init_rules() { add_rewrite_rule('^car/([^/]*)/([^/]*)/?','index.php?pagename=car&id=$matches[1]&make=$matches[2]','top'); } The rule I have added does not appear in the Monkeyman Rewrite Analyzer list and does not appear to make any difference to the site when trying to visit mysite.com/32423/testmake Any suggestions?
Did you flush the rules after making this code? Visit the Settings->Permalinks screen. This will cause a rule flush. Then check and see if your new rule appears.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "multisite, url rewriting, urls, rewrite rules" }
One custom loop with condition to check child posts I have one loop of pages with 999 page ID as a parent (pages from this loop have also another child pages) $args = array( 'post_type' => 'page', 'post_parent' => 999, 'order' => 'ASC', 'posts_per_page' => -1 ); $loop = new WP_Query( $args ); Now I want to get the pages, but with condition, when the page in the loop have child pages I would like to display another structure. <?php if ( have_posts() ) : ?> <?php while ( $loop->have_posts() ) : $loop->the_post(); ?> <?php if (condition if current post have subpages ) : ?> // html structure, <?php else : ?> // another default structure <?php endif; ?> <?php endwhile; ?> <?php endif; ?> I've tried with get_page_children, but with no success, I need only the proper condition. Thanks in advance for any help.
The appropriately named `get_children()` should be what you want. if ( have_posts() ) { while ( $loop->have_posts() ) { $loop->the_post(); $args = array( 'post_parent' => get_the_ID(), // the ID from your loop 'post_type' => 'page', 'posts_per_page' => 1, // you only need to know if you have children so one is enough 'post_status' => 'publish' ); $c = get_children($args); if (!empty($c)) { // html structure, } else { // another default structure } } } If you have more than a few posts in this loop you are going to be running a lot of queries on the page. You should consider caching the results.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "loop, conditional content" }
How to get list of paths (not urls) for an image I can get a list of urls for an image like this: $sizes = array_merge(array('full'),get_intermediate_image_sizes()); foreach ($sizes as $imageSize) { $image_attributes = wp_get_attachment_image_src( $post->ID , $imageSize ); echo $imageSize . ':<br>' .$image_attributes[0].'<br>'; } which gives me full: thumbnail: medium: What I want is full: /path/to/public_html/wp-content/_uploads/2014/01/my_image.png thumbnail: /path/to/public_html/wp-content/_uploads/2014/01/my_image-150x150.png medium: /path/to/public_html/wp-content/_uploads/2014/01/my_image-300x116.png
This should achieve what you want, however note that there will be backslashes AND forward slashes in the resulting path name. If this causes a problem on your web server you may need to do a further `str_replace` to forward slashes with backslashes See comments in code for more info $sizes = array_merge(array('full'),get_intermediate_image_sizes()); $uploads = wp_upload_dir(); foreach ($sizes as $imageSize) { // Get the image object $image_object = wp_get_attachment_image_src($post->ID,$imageSize ); // Isolate the url $image_url = $image_object[0]; // Using the wp_upload_dir replace the baseurl with the basedir $image_path = str_replace( $uploads['baseurl'], $uploads['basedir'], $image_url ); // echo it out echo $imageSize . ':<br>' .$image_path.'<br>'; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "attachments" }
How to delete a transient on post/page publish? I have a transient set for a custom query. It expires in 30 days. But I also need it to expire once a new post/page is published. So that the new published post/page is available in that custom query. How to delete a transient on post/page publish? How I set the transient: // Get any existing copy of our transient data if ( false === ( $query = get_transient('d_results') ) ) { // It wasn't there, so regenerate the data and save the transient $randargs = array("post_type"=>"", "orderby"=>"", "order"=>"", "posts_per_page"=>-1); $query = new WP_Query($randargs); set_transient( 'd_results', $query, DAY_IN_SECONDS * 30); }
I am considering it for publication of a new post. Add the below code in your active theme's **functions.php** file. function wpse_delete_query_transient( $post ) { // Deletes the transient when a new post is published delete_transient( 'd_results' ); } add_action( 'new_to_publish', 'wpse_delete_query_transient' ); This will delete the transient every time a new post is published. if you want to delete the transients on differrent post status transitions, you may like to look into the codex
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "query, transient" }
Taxonomy page shows category in title I have a custom taxonomy called 'Genres' within that I have various taxonomies: 'Paintings' 'Drawings' etc. I use the code below to create my page titles. When viewing the taxonomy page for 'Paintings' I get a page title 'Paintings | Genres | BlogName' whereas I wanted to display only: 'Paintings | BlogName', how can I do that? <title><?php /* Print the <title> tag based on what is being viewed */ global $page, $paged; wp_title( '|', true, 'right' ); // Add the blog name. bloginfo( 'name' ); // Add the blog description for the home/front page. $site_description = get_bloginfo( 'description', 'display' ); if ( $site_description && ( is_home() || is_front_page() ) ) echo " | $site_description"; ?></title>
You should use the `wp_title` filter, see: other question They are creating a separate function that handles the output.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, taxonomy, title" }
phpMyAdmin displays error when importing database I'm migrating a WordPress for a friend to a different server. I have already backed up all files and was given a copy of the database by the old server admin. The problem is that when I try and import the database using phpMyAdmin, I get this error message: `SQL query: -- -- Database: ``wordpress_6`` -- CREATE DATABASE ``wordpress_6`` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; MySQL said: Documentation #1044 - Access denied for user 'prvtres9'@'localhost' to database 'wordpress_6` I'm not sure what would initiate this error message, but the tiny amount of information I found out in several hours of frustration eludes that it could be in the way the database was copied, therefore putting me in a helpless position, but I don't want to approach the old server admin just to be wrong about this
If you have already created the database that you wish to import into and you have selected that database in PHPMyAdmin, but the import file is trying to create a new database, then you will see this error message. All you need to do is open up the SQL file in a text editor and delete the line that begins with `CREATE DATABASE` (it will be very near the top of the file). Now try the import again and it should import that data into your selected database rather than trying to create a new one.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, database, sql, import, phpmyadmin" }
Multisite and plugins options I need more information about `get_site_option()`, `update_site_option()` and `add_site_option()`. In codex they say it's the same as single install except that in multisite, it returns the network-wide option. Ok but I get confused on the this point : does it mean once network-wide option is set this option is the same in all sites? Or is it overriden per each site? I mean if I do this : update_site_option('option_group', 'default_options());// default_options() returns an array of default options Where will it save datas? And will each site get its own values for options after? It's quite unclear for me any hint will be cool.
Back when Multisite first appeared, there were multiple _blogs_ in a single _site_. The `*_site_option` functions are from that older Multisite era. Now in current Multisite you have multiple _sites_ in a _network_ , so the meaning of "site" has made a confusing change. In the context of these functions, think of them as _network_ functions and it may make more sense. They create and update options which are not associated to a particular site in your network, but are global to the whole network. If you want unique, per-site options, use the regular `add_option`, `update_option`, and `get_option`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite, options" }
Unicode characters are saved in a funny way in the DB I have a custom website in which I am using `wp_insert_post()` to manually create posts that have a title which has characters thare are non-English Unicode letters (Arabic to be more specific). The URL that gets created by `wp_insert_post()` is something similar to the following: < (note that I have permalinks enabled) Now, how do I prevent the above link from being saved as show? How do I ensure the Unicode characters are used instead of the %-and-number combination for each letter?
Do not touch that string. URLs must be percent-encoded, and what you see is the slug for the URL. A browser will display the characters just fine, so don’t worry about the database.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "urls, wp insert post, characters" }
How to display summary content from a Page (Not a Post) on another page I created a Page called "About Joe" as a **_page_** in WordPress. Then on a different page (e.g. the homepage), I wish to display _a summary_ which includes: 1. a thumbnail 2. the 1st paragraph 3. link to page Is this possible? Maybe I'm not asking the right questions to the codex as I'm not finding anything. The closest thing I could find was `get_page()`, which i'm not even sure is the solution. But that function is now **_deprecated_**. Please advise! Thanks
**Update: No more working tired!** Completely forgot about WP_Query. Here is what I came up with... <?php $args = array ( 'page_id' => '1265', 'post_type' => 'Page', 'post_status' => 'published', 'posts_per_page' => '1', 'ignore_sticky_posts' => true, ); // The Query $fa_query = new WP_Query( $args ); ?> <?php if ( $fa_query->have_posts() ) : while ( $fa_query->have_posts() ) : $fa_query->the_post(); ?> // do something <?php endwhile; else : ?> // Nothing to see <?php endif; ?> <?php wp_reset_postdata(); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "wp query, pages, frontpage" }
Meta title W3C Validation Error with On the single post, the WordPress generates the meta title automatically but it gives validation error. This is what WordPress generates: <meta name="title" content="The post title goes here" /> And this is the error I get: **Bad value title for attribute name on element meta: Keyword title is not registered.** How can this be fixed? Please help.
`title` is not part of the current HTML5 spec for meta element names. See here. The `<title>` element in the document head should be enough for metadata purposes.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, post meta, validation, html" }
Custom form in admin area, redirect in wrong page I'm writing a custom form on my plugin settings area. <form action="<?php echo admin_url('options-general.php?page=yasr_settings_page') ?>" id="form_add_multi_set"> <strong>Name</strong> <input type="text" name="multi-set-name" id="new-multi-set-name" class="input-text-multi-set"> <?php wp_nonce_field( 'add-multi-set', 'add-nonce-new-multi-set' ) ?> <input name="action" type="hidden" id="add-nonce-new-multi-set" value="new-multi-set" /> <?php submit_button(__('Create New Set', 'yasr'), 'primary'); ?> </form> When I try to click on submit I got redirect on options-general.php but I need to get redirect on options-general.php?page=yasr_settings_page. How to do that?
Just add the attribute `method="post"` within the `form` element. That's it :) Happy coding!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "forms, options" }
Register scripts located in child theme? I'm having a lot of trouble registering scripts located in a child theme folder: This works fine: function register_scripts() { wp_register_script( 'newsletter', get_template_directory_uri() . '/scripts/scripts.js', array( 'jquery-migrate' ), null ); } add_action( 'init', 'register_scripts' ); However it points to the parent theme folder and not the child, when I try to point to the child theme folder, nothing at all happens: function register_scripts() { wp_register_script( 'newsletter', get_stylesheet_directory_uri() . '/scripts/scripts.js', array( 'jquery-migrate' ), null ); } add_action( 'init', 'register_scripts' ); What am I doing wrong?
I think that none the options you has posted actually works. You are only registering the script, you need to enqeue them. Also, you should use `wp_enqueue_scripts()` action hook instead of `init()`. function register_scripts() { wp_register_script( 'newsletter', get_stylesheet_directory_uri() . '/scripts/scripts.js', array( 'jquery-migrate' ), null ); wp_enqeue('newsletter'); } add_action( 'wp_enqueue_scripts', 'register_scripts' );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "scripts, wp register script" }
Display Image Upload from Contact Form 7 on Redirect Page How would I show an image upload, a photo of someone, in the Thank You page. It's for a competition. NB: The user uploads an image and then that image is shown on the thank you page. * I need to access the form data array * find the file uploaded already * and display this in an img tag on the thank you page * I already have the redirect in place I'm not very good at all with PHP, but I feel like I've been skirting the solution I just can't see it. This question shows the possibility of using the data from the form but how would I extract the file variable and then use that to show it on the next page. It would need to be a method that can handle numerous people using the form possibly at the same time. There are likely to be hundreds of entries. Thanks in advance!
I solved this problem using the Contact Form DB plugin. 1. I used their HTML shortcode [cfdb-html] to call the img url saved to the wordpress database 2. Then I limited it to the most recent row (using the documentation available on their site) to make sure only the image was shown. 3. Some basic CSS finished it off.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "uploads, redirect, plugin contact form 7" }
Extending WP_List_Table seems getting wrong with $this->get_columns() - what's wrong? I'm trying to implement an Admin Table for a view page of a plugin of mine by following the following tutorial: * **Create Native Admin Tables In WordPress The Right Way** by _Jeremy Desvaux de Marigny_ SmashingMagazine.com Here's how I extended the `WP_List_Table` class for my plugin. (Code at Pastebin) The problem is: it's not showing any Column or Row, only the Table Top and Bottom. I did `var_dump()` steps, and found that in **Line 149** the `var_dump($columns);` is showing empty. !Extended List Table WHAT AM I DOING WRONG ABOUT THIS PORTION? /* -- Register the Columns -- */ $columns = $this->get_columns(); $_wp_column_headers[$screen->id]=$columns;
This, $_wp_column_headers[$screen->id]=$columns; ...is deprecated long ago. Instead you need to assign your columns to the following class property on `WP_List_Table`, $this->_column_headers = array( $this->get_columns(), array(), //hidden columns if applicable $this->get_sortable_columns() );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "plugin development, wp list table" }
Get section of input passed to the sanitize_callback How can I find out what section each input is in when viewing the `$input` array passed to the sanitize_callback function defined in `register_setting()`? I suppose one option is to include the section as part of the field name and can then extract it. E.g. `name="section^field"` and then in the sanitize_callback: foreach($input as $name => $val) { $parts = explode('^', $name); $section = $parts[0]; $field = $parts[1]; // do more stuff here } But this feels a little hacky. Is there a better way?
Unfortunately if you look at the source the only thing that happens there is: add_filter( "sanitize_option_{$option_name}", $sanitize_callback ); There is no opportunity to pass along or retrieve any extra information. On a larger scale I would say if you need section-specific sanitize then use section-specific callbacks. Even if considerable parts are shared with class based code it should be easy enough to neatly organize.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development" }
The entity "raquo" was referenced, but not declared Would anyone happen to know why I keep getting the error: "The URL does not appear to reference a valid XML file. We encountered the following problem: Error on line 163: The entity "raquo" was referenced, but not declared." When I put CmChatLive.com into feedburner? < I am unable to edit the output of that title entity.
I believe this forum post in the WordPress.org Support Forums will help. If you'd like me to research it more, I'll update this post as I go... I hate telling someone to disable something without having a fix when it's re-enabled.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "title, feedburner" }
get_post_meta is returning image id I'm using this script to get image filename, stored in a custom meta called background: $background = get_post_meta( '22', 'background', true ); echo $background; But it is returning the id of the image, not his filename.
`background` is not a Core meta field. Since you say that `get_post_meta( '22', 'background', true );` returns an image ID, I can only assume that whatever saved that value saved the image ID and not the filename. You can convert the filename to an URL with `wp_get_attachment_url()` or get other information including a partial file name with `wp_get_attachment_metadata()`
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "custom post types, metabox, post meta" }
wp-cli import theme sample data i am trying to create an automated process of installing a wordpress site from scrach (no db, no user, no files, no settings) to the point were the site is up and it has it's own custom theme with the sample data imported so i have 2 questions 1) wp-cli can help me do all this except importing the sample data xml that comes with the themes ... can anyone help me with a solution for this? 2) does anyone know of any attempt to automate the installation process of a wp site? thanks, Rares
I just filed to a PR to the WPTest.io "theme test data". In short it's the following series of commands. You just have to replace 1. The remote request provider. In the example it's `curl`, but you could use `wget` or others as well 2. The remote request target. In the example it's the `wptest.io` XML/WRX file. Code: #!/bin/sh # @TODO automate things like changing folders, chmod/permission, etc. curl -O wp import wptest.xml --authors=create rm wptest.xml where `wptest.xml` is the filename and of course you should run it from within the target folder.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "wp cli" }
Get post id by attachment id? I have attachment id, but can't find way to get post id by this attachment id. I can loop all posts and find it, but maybe exists easy way get it. Does anyone know a similar function?
`get_post_ancestors` can give you the ID of the object an attachment is associated with: $attachment_id = 42; $parent = get_post_ancestors( $attachment_id ); echo $parent[0]; // $parent will be an array
stackexchange-wordpress
{ "answer_score": 10, "question_score": 3, "tags": "posts, attachments" }
Wordpress register_post_type Invalid post type I am creating my own posts in wordpress however I have hit a little problem and im not sure how to fix it. The below register_post_type creates an Invalid post type error. add_action( 'init', 'create_post_type' ); function create_post_type() { register_post_type( 'talent', array( 'labels' => array( 'name' => __( 'Talent' ), 'singular_name' => __( 'talent' ) ), 'public' => true, 'has_archive' => true, ) ); } it doesn't seem to like the word talent. If I change 'talent' to 'arist' it works. However it needs to be 'talent' for the URL. Ive checked on wordpress and using talent shouldn't cause any conflicts with default wordpress settings.
If you can't get the "talent" post type to register, set the name to artist and then using the Rewrite option for the CPT e.g. 'rewrite' => array( 'slug' => 'talent' ), That will give you the URL you desire
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "post type" }
Adding in support thumbnail removes editor I have created a custom post type. And on the custom post type I would like to have a featured image. I have added the featured image to my custom posts however when I do this it removes the main text editor (which you use to add copy to your website). If i remove support thumbnail it brings the text editor back. add_action( 'init', 'create_post_type' ); function create_post_type() { register_post_type( 'artist', array( 'labels' => array( 'name' => __( 'Talent' ), 'singular_name' => __( 'talent' ) ), 'public' => true, 'has_archive' => true, 'supports' => array( 'thumbnail' ), 'rewrite' => array('slug' => 'talent'), ) ); }
You need to add each individual support you need e.g. 'supports' => array('thumbnail', 'title', 'editor'), The title and editor are added by default in a post type but if you add the supports query you need to redefine them back in.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "post thumbnails, post type" }
Limit file downloads to logged in users (WP + Nginx) I am looking for a way to restrict access to mp3 files on my site to logged in users only. The approach listed here sounds pretty much like what I need: RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} ^.*(mp3|m4a)$ RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC] RewriteRule . - [R=403,L] except how would I convert these .htaccess rules to nginx?
You could do it like this: location ~ \.(mp3|m4a)$ { if ($http_cookie !~ "wordpress_logged_in") { return 403; } } If it is really matters that it is secured (as opposed to just not being "obviously" accessible by the general public), auth should probably also be checked since it's quite easy to send the WP login cookie with the HTTP request, regardless of auth status.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "nginx, content restriction" }
Missing parent page attribute Suddenly the parent page attribute is missing on the page edit view. I'm using Wordpress 3.9.1 and the newest Avada theme. The parent attribute has worked. Now it is not shown as page attribute. I've updated Wordpress and the theme. It has not helped. I have switched the theme and set Avada back again and it worked for a short time. Now do not again. What can I do? Thanks!
Ok, I solved it myself. The Drop-down list is only displayed if there is at least one public page. Why there is not just "There is no public page" text instead of hiding the list without a hint!? I have set every page to private, so that the list was not displayed at all. If I have made a page ​​public, I could select it as a page attribute of a new created page.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "pages, page specific settings" }
check if a taxnomy queried in $wp_query? Is there a way to check if there is any taxonomy that has been queried in the global $wp_query?
`$wp_query->query_vars['taxonomy']` alone won't do it, but yes, you can check the object itself. However, something like `is_tax()` may be more appropriate. A lot depends on context and you query is all but lacking in that.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, wp query, advanced taxonomy queries" }
wp_list_categories() with attachment post types I'm working on a pictures gallery, where there is no 'regular' post, only images with several custom taxonomies, some of them being hierarchical. I use `wp_list_categories()` to display hierarchical lists of terms and that works fine provided I set the `hide_empty` parameter to `0`. However, I would like to display only terms that have pictures, or whose descendants have pictures. But I can't find a way to use `hierarchical` instead of `hide_empty`, probably because the function looks for terms attached to regular posts. Is there a way to change its behaviour and make it look for `post-type='attachment'` or whatever, so I could list only terms related to published pictures? Thanks for helping.
When you register your taxonomy, set the `update_count_callback` argument to `_update_generic_term_count`. This will count all objects associated to taxonomy terms so you don't need to use `hide_empty`. $args = array( // your other taxonomy arguments here 'update_count_callback' => '_update_generic_term_count' ); register_taxonomy( 'your-taxonomy', array( 'attachment' ), $args );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, categories" }
Multiple filter conditions for WP_Query I'm having a hard time figuring out how to accomplish this (really simple) task: > Get 4 random posts, but only select from the 10 most recent posts. This works great for the random part, but obviously selects from all the posts: $query = array( 'posts_per_page' => 4, 'orderby' => 'rand', 'post__not_in' =>array($post->ID) ); $wp_query = new WP_Query($query); Basically I want to take the results of one query: $firstquery = array( 'posts_per_page' => 10, 'orderby' => 'date', 'post__not_in' =>array($post->ID), 'order' => 'DESC' ); And pass the results into that first one. Any help would be super appreciated. I've looked at merging them but I think that just give me results from both? Little confused.
Run first query las 10 posts, than use `array_rand` PHP function on posts array: $args = array( 'posts_per_page' => 10, 'post__not_in' =>array( $post->ID ), 'orderby' => 'post_date', 'order' => 'DESC' ); $query = new WP_Query( $args ); if ( $query->have_posts() ) { if ( $query->post_count > 4 ) { $query->posts = array_rand( $query->posts, 4 ); // get 4 random posts $query->post_count = 4; // update post count // for pagination, if you need it $query->max_num_pages = (int) ceil( $query->found_posts / 4 ); } // After that loop as usual while ( $query->have_posts() ) : $query->the_post(); // loop here endwhile; wp_reset_postdata(); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "wp query, theme development" }
Call dynamic sidebar by name not ID Is there a way to call a dynamic sidebar by name rather than ID. Something like this: $postName = get_the_category(); dynamic_sidebar($postName->category_nicename . '_sidebar') ;
You can either pass Name or ID of dynamic sidebar to dynamic_sidebar. <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "sidebar" }
Wordpress redirect to splash page once a day for the first week How can I redirect the user to the splash page for the first week they ever visit only? This code would redirect it once every week, but I'm more after a once a day for 7 days solution: function checkAccessed(){ if ( !isset($_COOKIE['accessed']) ) { setcookie('accessed', 'yes', time() + 3600*24*7); define("ACCESSED", false); }else{ define("ACCESSED", true); } } add_action("init", "checkAccessed"); The splash page should permit the user to go to the home page between other links.
This can be achieved with Two Cookie. 1. Saves the unix time of user visits first time. Expiration time set to a higher value, A cookie that never expires. 2. Set another cookie that is valid for 24 hours. ## Code function wpse144762_check_accessed(){ if( !isset($_COOKIE['first_time']) ) { // user visiting for the first time setcookie('first_time', 'yes', time() + 60 * 60 * 24 * 365 * 10); // expires in 10 years define("ACCESSED", false); }elseif ( !isset($_COOKIE['accessed']) && intval($_COOKIE['first_time']) > time() - 60 * 60 * 24 * 7 ) { setcookie('accessed', 'yes', time() + 3600*24); define("ACCESSED", false); }else{ define("ACCESSED", true); } } add_action("template_redirect", "wpse144762_check_accessed"); _Code is not tested. But this should give you the idea_
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect, login" }
How to print the current post depth as update notification? I need to find a simple if-condition to print the current post-depth for parents as an update notification. The following code in the functions.php is not working, it is resulting in "0" for all posts, both for parents and childs. Can anybody help out on this? global $wpdb; global $post; $id = $post->ID; $depth = $wpdb->get_var("SELECT post_parent FROM $wpdb->posts WHERE ID = '".$id."'"); if($depth == '0') { function my_admin_notice() { ?> <div class="updated"> <p><?php _e( 'Depth is 0!', 'my-text-domain' ); ?></p> </div> <?php } add_action( 'admin_notices', 'my_admin_notice' ); }
You should wrap your condition inside the function, rather than the function inside the condition (this will also prevent errors with code running too early as WordPress loads). function my_admin_notice() { global $wpdb, $post; $depth = $wpdb->get_var( $wpdb->prepare( "SELECT post_parent FROM $wpdb->posts WHERE ID = %d", $post->ID ) ); if ( $depth == '0' ) : ?> <div class="updated"> <p><?php _e( 'Depth is 0!', 'my-text-domain' ); ?></p> </div> <?php endif; } add_action( 'admin_notices', 'my_admin_notice' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, children" }
How to add font in wordpress I have a oswald.woff font file downloaded from some free fonts site. Using ftp i have created folder called fonts in the themes folders. (i.e /wp-content/themes/esplanade/fonts). In the fonts folder i put the oswald.woff file. @font-face { font-family: "Oswald"; font-style: normal; font-weight: 400; src: local("Oswald Regular"), local("Oswald-Regular"), url("fonts/oswald.woff") format("woff"); } I use this font for an heading h1. When open my site, it says "www.mysite.com/fonts/oswald.woff" (mysite.com used for representation, its not the origianl site) not found in the firebug errors console. how to get the url of the file oswald.woff
It should be in www.mysite.com/wp-content/themes/esplanade/fonts/oswald.woff
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "theme development" }
Headers for Contact Form are wrong I am using a simple contact form I created myself that consists of just a script (php) and a WordPress shortcode. It works fine except the headers are saying something like [email protected] instead of displaying my admin email (or my correct email). Can someone see where my mistake is? Thank you. The two codes are here: Pastebin
Your 'From' header is not correctly formatted so it is defaulting to servers address. Try this... // create email headers $headers = 'From: iStudioFX <[email protected]>' . "\r\n" .
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, forms" }
Contact Form 7 submission does not complete I have a Content Form 7 Version 3.8.1 form which seems to function perfectly in that the validation events all work and when submit is clicked the console shows no error, a 200 response comes back from the post but no success message displays and the ajax-loader continues to display indefinitely. No email is received either. The form can be seen at < Here are the network and console tabs after submission: !network tab !console
There is a fatal error in the theme you are using. When I checked the response in firebug console, I got the following error **Fatal error** : Cannot use object of type WP_Error as array in **/home/content/s/b/r/sbrenan/html/peteshighway.com/wp-content/themes/peteshwy/functions.php** on line **96** Either you fix this or contact with the theme support team.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "jquery, ajax, plugin contact form 7" }
Wordpress Update Plugin Hook/Action? Since 3.9 I've researched this a few times, yet my searching does not reveal much except custom code which may or may not be good WordPress practice. As of the latest releases (WordPress 3.9 "Smith"), **has a hook been added to the plugin update process?** I'm asking because its a very basic need, yet I do not see it added to the codex (yet). If not, what is the common and best practice developers employ? EDIT: Just to clarify, I'm not talking about activation, but about updating, that way, if there are changes in database or otherwise it can be addressed.
I don't think an action has been added. You can look at version details for any version and see any new actions added. The WordPress Way to run code on plugin update is what is described here: > The proper way to handle an upgrade path is to only run an upgrade procedure when you need to. Ideally, you would store a “version” in your plugin’s database option, and then a version in the code. If they do not match, you would fire your upgrade procedure, and then set the database option to equal the version in the code. This is how many plugins handle upgrades, and this is how core works as well. and with code example here: function myplugin_update_db_check() { global $jal_db_version; if (get_site_option( 'jal_db_version' ) != $jal_db_version) { jal_install(); } } add_action( 'plugins_loaded', 'myplugin_update_db_check' );
stackexchange-wordpress
{ "answer_score": 19, "question_score": 17, "tags": "plugin development, actions, upgrade" }
How is the `get_sidebar` function meant to be used to call a 2nd sidebar? What's the proper way to call a second sidebar in the main home of my blog? And I mean 2 sidebars at the same time.... I might edit the question when I get further info, but now I'm feeling completely lost.
All that `get_sidebar()` really does is load a file. Which file you load depends on how you call the function. `get_sidebar()` will load `sidebar.php` from the theme directory. `get_sidebar('two');` will load `sidebar-two.php` from the theme directory. "Theme directory" means the same folder as should have `style.css`. That is all there is to using the function. Beyond that, I don't know what this question means.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, sidebar" }
Search Result from another wordpress website I am wondering, is it possible to get the search result from Website A and display it to Website B, assuming that both websites are not part of multisite?
Yes this will be possible. I would suggest integrating your WordPress websites search with Google search and then you can specify the site/s (in your cause Site B) you wish to search when a users performs a search on your current site (Site A) Here is a awesome and simple tutorial a-z tutorial on how to set it all up: < Goodluck :-)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "search" }
Warning after create Custom post type with Roots theme I've created e Custom post type with Roots theme, adding the custom script inside functions.php like require_once locate_template('/lib/custom-post-types.php'); // Custom post types After that in backend the list of pages is not displayed, and in frontend show this Warning: > Warning: strpos() expects parameter 1 to be string, array given in /wordpress/wp-includes/query.php on line 2375 > > Warning: urldecode() expects parameter 1 to be string, array given in /wordpress/wp-includes/post.php on line 3901 > > Warning: urlencode() expects parameter 1 to be string, array given in /wordpress/wp-includes/formatting.php on line 3690 What could be?
Solved, it was a problem with the custom-post-types.php I was calling the type with the name `'post_type'` changed that solved the issue.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, theme roots" }
change the Dashboard menu items label wp I need to change this word "Dashboard" in the top menu in wp-admin If anyone can supply the code for the functions.php file or point me in the direction I would greatly appreciate it!
Found here: add_filter('gettext', 'rename_admin_menu_items'); add_filter('ngettext', 'rename_admin_menu_items'); function rename_admin_menu_items( $menu ) { $menu = str_ireplace( 'Dashboard', 'Home', $menu ); return $menu; } Change home to whatever you want it to be
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "dashboard" }
query posts only works on the first page I'm using Jetpack's infinite scroll function on the homepage and I only want to display posts from the category with ID 1. The problem is that my query works correctly only on the first page. On the other pages it displays posts from all categories. Here you have my code <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; ?> <?php query_posts($query_string.'&cat=1&posts_per_page=12&paged='.$paged);?> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <?php get_template_part( 'content' ); ?> <?php endwhile; endif; ?> Do you know what's wrong with this? I'm using this code on multiple websites, but I don't have the infinite scroll there.
As @Pieter Goosen said, you shouldn't be using `query_posts`, nor running your own query. Instead, override the main query that already runs: function wpse_144974_pre_get_posts( $wp_query ) { if ( ! is_admin() && $wp_query->is_main_query() && is_home() ) $wp_query->set( 'cat', 1 ); } add_action( 'pre_get_posts', 'wpse_144974_pre_get_posts' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": -2, "tags": "query, plugin jetpack, query string, infinite scroll" }
Meta Box Only in CPT Edit Page, Not in Add New I have a CTP named `leads` and have 2 metaboxes added to the CPT new/edit screen. I need to have one of them only in edit screen, not in add new. Played with the codes provided in couple of answers, but they weren't of much help. (97845 and 89395) Can anyone help? I don't necessarily want anyone to do it for me, but a few playable starts would be great. Thanks
Check the `action` of the current screen object for `add`: function wpd_add_meta_box() { $screen = get_current_screen(); if( 'add' != $screen->action ){ add_meta_box( 'myplugin_sectionid', 'My meta box', 'myplugin_meta_box_callback', 'leads' ); } } add_action( 'add_meta_boxes', 'wpd_add_meta_box' );
stackexchange-wordpress
{ "answer_score": 6, "question_score": 1, "tags": "custom post types, metabox, post meta" }
Alternative to mysql_real_escape_string I have a WordPress plugin that at one point I need to see if a certain title exists in the database. For 2 years, this code worked fine: $myposttitle= $wpdb->get_results( "select post_title from $wpdb->posts where post_title like '%". mysql_real_escape_string($myTitle) . "%'" ); However, with php 5.5. and WP 3.9.1, this causes an error because the function `mysql_real_escape_string` is deprecated. Any ideas on what other function will properly escape the contents of `$myTitle` now that I can't use `mysql_real_escape_string` anymore? Thanks
When working with database in WordPress you should never use the low lever `mysql_*` or `mysqli_*` functions. Always use `$wpdb` methods, in your case you should use `prepare()`: $query = $wpdb->prepare( "SELECT post_title from $wpdb->posts WHERE post_title LIKE %s", "%" . $myTitle . "%" ); Moreover, once you are getting a single column, you have easier life using `get_col` instead of `get_results`: $myposttitle = get_col( $query );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "mysql, wpdb" }
How to import XML to Wordpress as post and custom fields? I need to import content (daily) from a xml file into wordpress. I am not looking for a specific answer, and I don't expect someone to write the whole code here, I just need some guidance on how to accomplish it. I plant to: 1. Write php script to load XML file with simplexml_load_file() 2. Read the file with SimpleXMLElement() 3. Put everything in a loop and use wp_insert_posts to create each post 4. I am going to use ACF for custom fields, not sure if ACF has function to do that programmatically. 5. Run everything with a cron job Does the above seems logical? Or am I going about it the hard way. I would appreciate if someone with more experience importing XML files could give me some tips, or things to consider. Thanks.
Sounds like a sound approach to me! Not enough rep to comment so I'm posting an answer... Only advice I'd have is to 1\. Make sure character encodings are correct so you don't end up with a bunch of "æÃ" 's 2\. Make database backups :-) As to ACF, I think it's pretty much the same as the "add_post_meta" function. Maybe it has a separate one in its API. But that's easy stuff.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "import, xml" }
Echo out element to another page. I have a small plugin that displays how many submissions are left on current ninja form. And writes it out as so <p id="submissions-left">hurry only 25 submission left. <\p> And tacks it onto the end of the form. How can I get that p tag to another page? Anyway to target the id and echo it out on another page? Say have a shortcode to use? Thanks
Well, writing `echo ninja_forms_field_submission_left_display( $field_id, $data );` into a template should do it, if `$field_id` and `$data` is correct. Creating a shortcode should be equally trivial: function field_sc_wpse_145003($atts,$content) { if (!isset($atts['field_id'])) return; return ninja_forms_field_submission_left_display( $atts['field_id'], $atts ); } add_shortcode('fieldfc','field_sc_wpse_145003'); echo do_shortcode('[fieldfc field_id="abc" default_content="def"]');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, php, shortcode, forms" }
Theme: Twenty Thirteen Mobile Sliding Menu Doesn't Bump Content Down I have created a child theme for Twenty-Thirteen and somewhere while editing it I broke the mobile menu slider as it no longer pushes the content down and instead displays behind the content. I've changed the CSS in someway to cause this issue but I cannot find what has caused it. I am hoping that the cause will be more apparent to someone more familiar with CSS than I. To view this issue you must resize your browser to width of less than 700px or so and click the menu button revealing the slider menu and the content overlap issue. Note how the H1 tag "Quad Cities, Chicago, Des Moines Photographer Brian Barkley" is over top menu. Here is a link to the site: < and here's a copy of the stock twenty thirteen to help compare < Here's an image to see for yourself what I am speaking of. !enter image description here
You've got a static height set on a block-level element: style.css:806 /** * 4.1 Site Header * ---------------------------------------------------------------------------- */ .site-header { position: relative; background: url( no-repeat scroll top); height: 100px; } remove the `height: 100px;` and it should work like you expect.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, css, mobile, theme twenty thirteen" }
How do I remove specific styles from the parent theme css using the child theme css? There are some styles in my parent theme that I would simply remove from the stylesheet if I was not using a child theme. Obviously, I do not want to remove them from the parent css, but is there a way to effectively "remove" the styles using my child theme?
The only way to "remove" styles from the parent theme is to override them in your child theme's css. For example if you have the following declaration in your parent theme: .someclass{ width: 200px; float: left; } You can override the width and float by declaring the following in your child theme: .someclass{ width: auto; float: none; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 4, "tags": "css, child theme" }
Activated plugin is stored as an object, rather than as a path This seems like a very unusual behavior: Usually, when activating a plugin, a path to the plugin's main file (or bootstrap) is stored in the database under `options.active_plugins`. However, something in the following code is causing Wordpress to store the object itself, rather than a path to it, in the database. Here is the plugin's bootstrap file (`bootstrap.php`): /** * Plugin metadata */ require_once( plugin_dir_path( __FILE__ ) . 'MyPlugin.php' ); $plugin = new MyPlugin(); $plugin->init(); After activation, the `active_plugins` option entry will look like this (retrieved using `get_option( 'active_plugins' )`: Array { [0] => (object) MyPlugin } When the expected result would be: Array { [0] => bootstrap.php }
You should just not add code outside of actions (callbacks attached to hooks and filters). Else your variables might conflict with global variables. The default/first action for a plugin bootstrap would be (depending on the type of plugin): `plugins_loaded` or `muplugins_loaded`. Attach hooks from there on to `wp_loaded` if you want stuff to run on `init` (but make it multisite save - `init` has other drawbacks as well).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, activation" }
Search Query that Includes Custom Table I have a WordPress website that grabs product data from a custom table. I would like to be able to also search from fields in the custom table. Could someone provide a sample query of what this would look like? I cannot join the custom table to the posts table because the custom table has data that is not associated with any other database tables (unless I am misunderstanding joins). The end goal is to show all posts and custom table data that match the specified "s" variables data. Thanks! UPDATE Here is the requested table structure of the custom table: !enter image description here Just to clarify, I am trying to modify the WordPress search so that it searches the posts table using a like query. I also need it to return results that match from the custom table as well. I will need it to search the subarticle and Article fields of the custom table.
I managed to solve this by taking s_ha_dum's suggestion to use a UNION. It is as follows: (SELECT ID, post_status, post_title, post_excerpt, post_content FROM wp_posts WHERE ((`post_title` LIKE '%diamond%') OR (`post_excerpt` LIKE '%diamond%') OR (`post_content` LIKE '%diamond%')) AND (`post_status` = 'publish' )) UNION (SELECT ref, StoreID, Article, subarticle, description FROM wp_hwproducts WHERE (`article` LIKE '%diamond%') OR (`subarticle` LIKE '%diamond%') OR (`description` LIKE '%diamond%')) ORDER BY `post_status` DESC;
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, search, wpdb, table" }
Wordpress how to create grouping like category **Wordpress how to create grouping like category** As my wordpress site is writing reviews on Television shows, and they have actors and actress. I would like to create a grouping that goes by the actor/actress name. Lets say "Actor Andrew act in TV Superman and TV Spiderman while Actor Milley act in TV Superman and TV Batman" I want link Andrew to Television show "Superman & Spiderman" while Superman itself is a category and Spiderman itself is a category because the posts in Superman like Superman Episode 1, 2 and so on.. Then we post pictures, word and summary per episode. How do I actually create an additional grouping in wordpress that I can contain the actor/actress name and bind it to category(The Television show)
You could use tags or categories to create these groupings. Here is an article on it that should be useful to you. <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins" }
wpdb insert and boolean fields I'm preparing an insert query like this: $wpdb->insert('table', $data, $format); data array will be: $data = array_push($data, 'resp' => true) problem is, what $format shall i use for a boolean field? $format = array_push($format, '%%') in the codex i found only %s (for strings) %d (for integers) and %f (for floats)...but what about booleans?
`BOOL` or `BOOLEAN` are as far as MYSQL is concerned just replacements/synonyms for `TINYINT(1)`, tiny integer, so using `%d` for integers is the correct way to do it. _Some additional information:_ * Codex: Class Reference - wpdb - Placeholders * MySQL: Numeric Type Overview * MySQL: Boolean Literals * MySQL: Integer Types
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "mysql, wpdb" }
OOP and WordPress shortcode I tried to add a shortcode this way class MyPlugin { function __construct() { $this->make_shortcode(); } function ShowMsg($cls, $lst4) { $data = shortcode_atts(array('phn' => '', 'msg' => ''), $atts); return 'You sent '.$data['msg '] .' from '.$data['phn'] ; } function make_shortcode() { add_shortcode('ShowMsg', 'ShowMsg'); } } new MyPlugin; And `[ShowMsg phn="123456" msg="Test Message"]` isn't working, it's returning full shortcode instead of desired text. I need your advice to fix.
That is not the way you add an object method as a callback. function make_shortcode() { add_shortcode('ShowMsg', array($this,'ShowMsg')); } This is explained in the Codex as it pertains to actions and filters, but the principle is the same. I should add that anonymous classes make for painful debugging. Instantiate that class to a variable. It will save you headaches.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 0, "tags": "shortcode, oop" }
Attributing a version number to a child theme's main stylesheet In header.php, I like to attribute a version number to the stylesheet so that the browser gets forced to refresh it. But when working with a child theme, its stylesheet is not explicitely called, rather WordPress automatically seeks it. So how or where to attribute a version number to the child theme's stylesheet?
You can update the version in the child themes style sheet itself... /* Theme Name: Twenty Fourteen Child Theme URI: Description: Twenty Fourteen Child Theme Author: John Doe Author URI: Template: twentyfourteen Version: 1.1.2 <---- Update here */
stackexchange-wordpress
{ "answer_score": 6, "question_score": 16, "tags": "child theme, css" }
Get current user array into hyperlink I am unsure how to take data from the user array and place some of these values into the following hyperlink. I want to replace the email address, first name and last name with the values from the currently logged in user array. <a href=" <?php $current_user = wp_get_current_user(); /** * @example Safe usage: $current_user = wp_get_current_user(); * if ( !($current_user instanceof WP_User) ) * return; */ echo 'Username: ' . $current_user->user_login . '<br />'; echo 'User email: ' . $current_user->user_email . '<br />'; echo 'User first name: ' . $current_user->user_firstname . '<br />'; echo 'User last name: ' . $current_user->user_lastname . '<br />'; echo 'User display name: ' . $current_user->display_name . '<br />'; echo 'User ID: ' . $current_user->ID . '<br />'; ?>
I would set up an array with the variables you want in the url query string and then use http_build_query(). Like so: $args = array( 'AT' => 'EN', 'AE' => $current_user->user_email, 'FN' => $current_user->user_firstname, 'LN' => $current_user->user_lastname, 'MK' => 665080128, 'PW' => 'miami', 'BU' => ' ?> <a href=" echo http_build_query($args); ?>">LINK</a>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "users, array" }
Is it possible to export WordPress from command line? Is it possible to export WordPress from command line? I don't mean use `mysqldump` to export the database, but create the xml file used to easily import to another WordPress installation.
Check out < It's fantastic and I've used the export capability multiple times. More information on wp-cli. > WP-CLI is a set of command-line tools for managing WordPress installations. You can update plugins, set up multisite installs and much more, without using a web browser. You will most likely have to install wp-cli. You can find instructions on wp-cli.org. There are also alternative installation instructions here: < To export your posts using wp-cli, you can use the command. wp export There are many options to limit the export by date, post type, category, author, etc. Most details can be found on this page: < I don't know of any other way to export an xml file from the command line.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 6, "tags": "export, xml, command line" }
Replace all media (images) I created a new theme for my Wordpress site and I need to replace all the media (images) on the site, since I am using all new image sizes (which are larger than the largest on my current site). 98% of the images will use the same names. Each post only contains one (featured) image and there are no images within the content area of the posts, so this makes the job slightly easier. I was wondering what the best (and cleanest) way was to go about doing this. I have considered the following: * Using a Wordpress plugin * Manually removing the featured images from all of my posts, deleting them and then manually adding the new images * Deleting all my media in my uploads folder and replacing them with the new images then re-generating the image sizes via a plugin I was wondering if there were any other easier and cleaner ways to do this. Most of the ways I suggested above would add downtime to my site while I get all this done.
This plugin, < is more efficient way to replace images
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "plugins, theme development" }
Can I make Wordpress use a custom template for a child page I have a custom post type called communities. Then I have the appropriate single-community.php page. Works great! So we want to use some of these "communities" as parent pages. Then underneath them we'd have multiple child pages. Can I have the parent pages use single-community.php and the child pages use single.php or something similar?
You can filter `template_include` and replace the `single-community.php` with a `single-child-community.php`. Example add_filter( 'template_include', function( $template ) { if ( ! is_singular() ) return $template; // not single if ( 'communities' !== get_post_type() ) return $template; // wrong post type if ( 0 === get_post()->post_parent ) return $template; // not a child return locate_template( 'single-child-community.php' ); });
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "custom post types, page template, child pages" }
Combining wp_current_user() and a variable I want to match a custom field in a user's profile to a particular post the user might be on. So I've got the custom fields for user profiles setup, and they're all numeric. Then, if I'm on a post page, I want to check if that post's ID matches the custom field in their profile. Something like this, where the custom field in the user's profile is `badge-id-2000` $current_user = wp_get_current_user(); $badge_ID = $post->ID; if ($badge_ID == $current_user->badge-id-$badge_ID) { return true; } Apparently on line 3 there where I'm using `badge-id-$badge_ID`, the variable doesn't work in that scenario. Is there some other way of doing this or getting the variable to work there?
What you have is mostly just PHP errors. First, dashes are not valid characters in variable names, so are going to have trouble with this-- `badge-id-$badge_ID`\-- no matter what. You should be using underscores instead. Second, you need to construct the entire object variable string beforehand, rather than try to construct it as you are using it. For example... $badge_ID = $post->ID; $badge_str = "badge_id_{$badge_ID}"; if ($badge_ID == $current_user->$badge_str) { echo 'Yay'; } Third, I am pretty sure you data structure is more complicated than it needs to be. You have to have an odd construction for `badge_id_*` like `$current_user->badge_id_123 = 123;` with numerous different badge ID object variable names, when you could just have `$current_user->badge_id = 123`. If you did that, you could simply this to: $badge_ID = $post->ID; if ($badge_ID == $current_user->badge_id) { echo 'Yay'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions" }
Conditional Javascript based on WP Version How would I go about creating a conditional statement in PHP to load a javascript file dependent on the active version of the WP installation? i.e. if using Wordpress 3.8 load javascript file A, if using Wordpress 3.9 load javascript file B.
You can do this with the function `get_bloginfo()`. There is a special paramater called `version` that retrieves the wordpress version from the `$wp_version` variable set in wp-includes/version.php. So you could do something like this function register_jquery_wp_version() { global $wp_version; if ( $wp_version >= 3.8 ) { // register and enqueue jquery A }elseif( $wp_version >= 3.9 ) { // register and enqueue jquery B } } add_action( 'wp_enqueue_scripts', 'register_jquery_wp_version' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, wp enqueue script, wordpress version" }
Why is the $old_instance needed for the widget update function? In the PHPdoc of the function `WP_Widget::update()` located under `wp-includes/widgets.php` it says the following: /** * ... * This function should check that $new_instance is set correctly. * The newly calculated value of $instance should be returned. * If "false" is returned, the instance won't be saved/updated. * ... */ It is unclear to me why the `$old_instance` is needed when updating the values and how can it be used to validate that the `$new_instance` is set correctly.
As the comment says, you should validate the values of the new instance. What happens if one of these values is invalid? You can either set a predefined default value or use the value from the old instance, because that must be valid. So a very simple update code could look like this: function update( $new_instance, $old_instance ) { return array_merge( $old_instance, $new_instance ); } There is no better way to get this information, so WordPress just passes it along in case you need it. But you are free to ignore it completely.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 5, "tags": "widgets" }
How to manage a particular "order by" for get_search_query()? How to manage in the search.php file the order of a posts search query managed with the following code <?php echo sprintf(__('%s Zoekresultaten voor ', 'website'), $wp_query->found_posts); echo get_search_query(); while (have_posts()) { the_post(); ?> <article> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <p><?php the_excerpt(); ?></p> <span class="datePost"><?php the_time('j-M-Y H:i'); ?></span> </article> <?php } ?> Is it possible to chose a field to order the search results? My goal should be to sort them according the time of the post managed with the function `the_time('j-M-Y H:i');`.
You can use the parse_query action hook, and set the orderby and order paramenters. function my_mod_search($query) { if ($query->is_search()) { $query->query_vars['order'] = 'ASC'; $query->query_vars['orderby'] = 'post_date'; } } add_action('parse_query', 'my_mod_search');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "query, search, sort, order" }
Copy a file from a plugin into my theme directory I coded a wordpress plugin using php's 'copy()' to copy a file from my plugin directory to my theme directory, but it's not working: <? function file_replace() { $plugin_dir = plugin_dir_path( __FILE__ ) . '/library/front-page.php'; $theme_dir = get_stylesheet_directory() . 'front-page.php'; copy($plugin_dir, $theme_dir); if (!copy($plugin_dir, $theme_dir)) { echo "failed to copy $plugin_dir to $theme_dir...\n"; } } add_action( 'wp_head', 'file_replace' ); I thought maybe I should use `! $wp_filesystem->put_contents()` but I'm not exactly sure how to do that or if that would even be the right way to go. Any ideas on the best way to copy a file from a plugin to a theme directory? Thanks
To answer your question, you have specified the paths incorrectly: `plugin_dir_path( __FILE__ )` already has a trailing slash at the end (having two trailing slashes should not be a problem, but safer is to have one) and `get_stylesheet_directory()` comes with no trailing slash at the end, so you have to add one before adding the filename. Your final code should be like this: <?php function file_replace() { $plugin_dir = plugin_dir_path( __FILE__ ) . 'library/front-page.php'; $theme_dir = get_stylesheet_directory() . '/front-page.php'; if (!copy($plugin_dir, $theme_dir)) { echo "failed to copy $plugin_dir to $theme_dir...\n"; } } add_action( 'wp_head', 'file_replace' );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 4, "tags": "wp filesystem" }
custom sort posts in archive/taxanomy page I want to override the default sort order of posts in archive and taxonomy pages. what hooks should I implement?
Put something along these lines in your functions.php: add_filter( 'pre_get_posts', 'custom_get_posts' ); function custom_get_posts( $query ) { if( is_category() || is_archive() ) { $query->query_vars['orderby'] = 'name'; $query->query_vars['order'] = 'ASC'; } return $query; } reference here (see the second answer)
stackexchange-wordpress
{ "answer_score": 5, "question_score": -1, "tags": "posts, wp query, archives, sort" }
Changing permalinks and redirecting urls I'm moving a client from Tumblr > WordPress. I can't figure out how to make the new permalinks work. Two issues: 1. The current Tumblr urls look like this: < But when I import the posts to WP, it chops off the end of the urls. I end up with just: < **So, question 1:** Can I append a slug to the end of that number? I've found a handy script that will rewrite the urls for me, removing the numbers and leaving me just with /post-name. But I'd like to keep that number in there. 2. The url of the site is changing from < to just < **So, question 2:** Can I accomplish a proper redirect with a 301 directive in my htaccess file?
For the first question, you would need a rewrite plugin, as WordPress wouldn't be able to handle the numbers in that string otherwise (it would see every site as a 404 Not Found), as slugs can't contain slashes of any kind. Ideally I think your best approach would be to set the post names without the digits (to make them human readable), and then use a plugin such as the Redirection plugin to forward requests to the old URL (with numbers) to the new one (you can set up a regex redirection here, so a simple rule to strip out just the numbers, or you can do one redirection per URL if you want to be extremely thorough). As for the permanent 301 redirect for removing the blog sub domain, the plugin mentioned above can handle this as well. Manually editing the .htaccess file isn't advised as plugins or themes may issue a hard refresh which overwrites the content of that file.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "redirect, tumblr" }
How to update plugins with database updates if I use svn I have my own SVN repository that has everything checked in from root of the htdocs directory. The repository includes (I do have some ignores set): * Wordpress Core * Plugins * Themes My process is: * update my repository on a development site first to test * commit the changes * svn up the production site My question is: * If a plugin installed has database updates attached to the newer version how are those updates applied in my production instance? I do know that Wordpress core has checks in place to see if the db is updated to the newest version, but I'm unable to find the same information out regarding plugins.
This will not be a problem. WordPress doesn't provide plugins with an explicit update hook for this reason: > If a plugin is manually updated then this upgrade hook won't fire. The best way to manage database upgrades is to do it the same way as WordPress does it. Store an option containing your plugin's database version and check it on the admin_init hook and run the upgrade routine when it doesn't match the version in your plugin. Many popular plugins use this method. It's definitely the most fool-proof. [From ticket #19681] So, each plugin has to do its own check to see if its database version is up to date. Plugins will generally run this check each time WordPress runs, or each time the admin panel is accessed, and update their database if needed. So if the plugin has database updates, they will probably be applied the first time someone visits the site after you run `svn up`. (Or, for some plugins, until someone visits the administration screens.)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, updates, svn" }
Error in database connection I am using Wamp server, I want to develop website using WordPress. I have configured wp-config.php. Still it is showing me > Error establishing a database connection. How should I solve this error?
try deleting `wp-config.php` or rename it, then go to your site, then follow the setup instructions. by deleting `wp-config.php` it will make your site run setup wizard when you visit your home page. It will ask you your database configuration. And if you fill out each input fields with correct data, then your site is good to go. Otherwise, your problem lies on your database host.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "wp config" }
Modify Search Query if original Query gave no results I'm looking for a way to modify the search query if the performed query returned no results. Let's say I'm looking for "Opening times", so I go to this URL: Now, in my `search.php` I want to check if that query gave no results, and in that case, I want to perform a new query with a different term, wihtout any required action by the user. Something like this: global $wp_query; $total_results = $wp_query->found_posts; if ( $total_results == 0 ) { // Create a new query with the terms 'Find Us' } // Display results (either those for the 'Opening times' query or for the 'Find Us' one if the former didn't return any result) Is there an easy way to do this?
You should create a custom query inside if. if ( $total_results == 0 ) { // Create a new query with the terms 'Find Us' $query = new Wp_query('s=Find Us'); if ($query->have_posts()): while ($query->have_posts()):$query->the_post(); //whatever you want to do with the result endwhile; endif; wp_reset_postdata(); } You can refer Creating a search page and Wp_query class referrence for more detail.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "wp query, query, search" }
Print string to footer using wp_footer option add_action('wp_footer','slider_option'); function slider_option() { $option ="<script>script function data </script>"; echo $option; } I want to print or you can say insert data in `$option` variable to footer menu Any suggestions?
Do you have to use a variable for you script? I have done this in the past and has worked... // add script to the footer and break out of PHP function slider_option(){ ?> <script>script function data</script> <?php } ?> add_action('wp_footer','slider_option'); If this does not work make sure you have the footer hook in you themes footer template file. <?php wp_footer(); ?>
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "variables, footer" }
How to show all of aspecific post type that has taxonomy and a specific term i have a post type called directory_listing, i have a taxonomy called 'place' and I have terms in that tax for place1 and place2. I need to display all the 'directory_listing' posts that use the term place2 of taxonomy 'place' in a custom page template. this is as far as i got, i am lost. <?php $pages = get_posts(array( 'post_type' => 'directory_listing', 'numberposts' => -1, 'tax_query' => array( array( 'taxonomy' => 'place', 'field' => 'slug', 'terms' => ('place2'), 'include_children' => false ) )) ); foreach ($pages as $page) { echo $pages->post_title . '<br/>'; echo $pages->post_content . '<br/>'; echo $pages->slug . '<br/><br/>'; } ?>
Why that `$pages` suddenly became `$myposts`!!? Anyway, I really don't see any big issues with your code, however, you can try this.. <?php $pages = get_posts(array( 'post_type' => 'directory_listing', 'posts_per_page' => -1, 'tax_query' => array( array( 'taxonomy' => 'place', 'field' => 'slug', 'terms' => 'place1', 'include_children' => false ) )) ); foreach ($pages as $page) { echo $page->post_title . '<br/>'; echo $page->post_content . '<br/>'; echo $page->slug . '<br/><br/>'; } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, custom taxonomy, customization, custom post type archives" }
Remove 'Visual' tab from TinyMCE editor I would like to disable the 'Visual' tab so that the 'Text' tab is always used. Is there a clean way to do this besides just doing something like .wp-switch-editor { display:none!important; } !enter image description here
I can think of three way you can do this 1. Log in to the Admin Control Panel and go to: Users -> All Users Find your username and click on Edit. Check "Disable the visual editor when writing" 2. Add this code in the themes function.php file add_filter( 'user_can_richedit' , '__return_false', 50 ); 3. Install a plugin like Disable Visual Editor WYSIWYG
stackexchange-wordpress
{ "answer_score": 8, "question_score": 2, "tags": "tinymce" }
Display A list of Admins I have a function that allows me to display ALL users on my site, but I was wondering if there was a way to display Admins and Contributors in a separate loop? My current function: function contributors() { global $wpdb; $authors = $wpdb->get_results("SELECT ID, user_nicename from $wpdb->users ORDER BY display_name"); foreach($authors as $author) { echo "<li>"; echo "<a href=\"".get_bloginfo('url')."/?author="; echo $author->ID; echo "\">"; echo get_avatar($author->ID); echo "</a>"; echo '<div>'; echo "<a href=\"".get_bloginfo('url')."/?author="; echo $author->ID; echo "\">"; the_author_meta('display_name', $author->ID); echo "</a>"; echo "</div>"; echo "</li>"; } }
Use get_users function it allows you to query user by role. For contributors, $contributors = get_users('role=contributors'); foreach($contributors as $contributors){ // do something with contributors } For Admins, $admins = get_users('role=admin'); foreach($admins as $admins){ // do something with admins } replace role=* with your desired roles.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "author, list" }
Redeclare a function in a child theme I want to redeclare a function that I inherited from the parent theme. When I do it in functions.php, I get a fatal error that redeclaration is not possible. I did a workaround: creating a modified function name and copying all the template files, index.php etc. into the child theme's directory and rewriting the function calls. So now the new function is called. This works but ignores any updates that the parent theme would have. Is there a better solution to this?
Redeclaring a function in a child theme only works when the parent themes' function is wrapped in a if( !function_exists( 'function_name' )): condition. Then you can simply just copy the complete function to the child theme and do whatever modifications you need to do. If the parent themes' functions aren't wrapped in that `if` conditional statement, and if no filters or hooks are supplied in the function, it will be best to copy the function to your child theme, rename that function, do your modifications and then update your template files accordingly to reflect the new function.
stackexchange-wordpress
{ "answer_score": 9, "question_score": 7, "tags": "functions, child theme" }
How to add user roles? I need to build a news site with 16 user roles. How can I add more user roles? By default I see 4 roles: * contributor * author * editor * administrator
What you want is `add_role()` The Codex provides sample code: $result = add_role( 'basic_contributor', __( 'Basic Contributor' ), array( 'read' => true, // true allows this capability 'edit_posts' => true, 'delete_posts' => false, // Use false to explicitly deny ) ); if ( null !== $result ) { echo 'Yay! New role created!'; } else { echo 'Oh... the basic_contributor role already exists.'; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": -4, "tags": "user roles" }
How can I safely use $_SERVER['REQUEST_URI'] to avoid XSS? I've seen a lot of warnings about using `$_SERVER['REQUEST_URI']` because it can open things up to XSS, but I haven't been able to find anything confirming a safe way to use it. Some people have mentioned using `esc_url()`, but I wasn't able to find anything confirming how to safely use it. This is my best guess, would this safely prevent XSS attacks? `echo esc_url(( is_ssl() ? ' : ' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);` If I want to use the URL internally rather than display it, it seems I have to use `esc_url_raw()`. Is this safe as well? `$pageurl = esc_url_raw(( is_ssl() ? ' : ' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);`
If you are printing the URL out, say to the front end... that is, it is to be displayed as a normal URL to a visitor etc. then: esc_url() If you are going to use the URL in, say, a WordPress redirect (or anything else that sends http header 'location', then you will need: esc_url_raw() This is actually the basis and fix of this recent security vulnerability: <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "security" }
How to set a cookie based on a page Get variable? I am trying to set a cookie, based on a GET variable from a page. The page URL looks like: `mysite.com/?my_var=somevalue` I'm trying this, but can't see what I'm doing wrong.. // make 'my_var' available as get_query_var('my_var').. function add_query_vars_filter($vars){ $vars[] = "my_var"; return $vars; } add_filter('query_vars', 'add_query_vars_filter'); add_action('init', 'my_setcookie'); // take the query_var 'my_var' and set it as cookie 'my_cookie' function my_setcookie() { setcookie('my_cookie', get_query_var('my_var'), strtotime('+1 day')); } Would love a little help with this! Thanks in advance.
On the page where you want to set the `cookie` write this code and check if(get_query_var('my_var') == 'somevalue'){ setcookie('my_cookie', get_query_var('my_var'), strtotime('+1 day')); } If we go with your code then it will set `coookie` on every page who having query variable `?my_var=somevalue`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, cookies" }
Are mu-plugins plugins still deployed via wordpress.org/plugins? I'm getting ready to publish my first plugin. I've decided to put it in mu-plugin, because if you removed it, it would break other code dependent on it. (It's a developer tool for logging variables to a text file.) So, do can I submit this to wp.o? Or do they only accept plugins that go into the plugins directory?
No, mu-plugins cannot be updated from wordpress.org. When you submit a plugin to that repository, it will be available as a regular plugin only. You can ask your users to isntall it as a mu-plugin, but they will not receive updates then. The “other code” should be written in a way that it doesn’t do _anything_ when your plugin is disabled. This is much better than using the mu-plugins directory.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, mu plugins" }
How to hide, and not to remove the attributes metabox? I need to **hide** , and not to remove the attributes meta box in the backend. The following code is removing the metabox: function hide_meta_box_attributes() { remove_meta_box('pageparentdiv', 'post', 'normal'); } add_filter('add_meta_boxes', 'hide_meta_boxes_attributes'); The problem is, that I am running hierarchical posts, which means I need to have the possibility to have posts and subposts which is enabled by this metabox. When I am removing the metabox, the functionality is not working anymore. But for my authors, I need to hide these attributes metabox. Anybody has a clue how to get a solution on this?
The `get_hidden_meta_boxes` function (source link) provides two filters that you can use to hide the meta box. (Pick just one of them.) The first is `default_hidden_meta_boxes` (source), adding the metabox to the $hidden array will hide the metabox by default, but the user can select the screen options tab and choose to enable it. The second filter is called `hidden_meta_boxes` (source), adding the metabox to the $hidden array here should just hide that metabox, period. Example using `hidden_meta_boxes` filter: function hide_meta_box_attributes( $hidden, $screen) { $hidden[] = 'pageparentdiv'; return $hidden; } add_filter('hidden_meta_boxes', 'hide_meta_box_attributes', 10, 2);
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "functions, metabox" }
How to make the 'delete' button inactive on some categories? As currently there's no way to declare any new custom post format in WordPress (3.9.1), is there a way I can make the 'delete' button on some categories inactive, so that the Editor can't remove them, and I can call them where necessary with their IDs without any hustle. !delete button in categories I just want it for some specific Categories only -- not for all.
WordPress uses the `WP_List_Table` class, or some extension of it, to generate those lists. In this case, it is the `WP_Terms_List_Table` class. That class contains a filter called `{$taxonomy}_row_actions`. add_filter( 'category_row_actions', function($actions, $tag) { $no_del = array(11,22,33); if (in_array($tag->term_id,$no_del)) { unset($actions['delete']); } return $actions; }, 10,2 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "categories, filters, post formats, customization" }
Wordpress query portfolio posts On my template I have this code <div class="blog_block"> <?php wp_reset_postdata(); ?> <?php $nbmax= 9; ?> <?php $tarali_query = new WP_Query('posts_per_page='.$nbmax.'&ignore_sticky_posts=1&paged='.$paged); ?> <?php while ($tarali_query -> have_posts()) : $tarali_query -> the_post(); ?> <?php get_template_part( 'content-blog', get_post_format() ); ?> <?php endwhile; ?> <?php tarali_paging_nav(); ?> </div><!-- blog_block --> Which render **ALL** recent posts of my blog. How can I modify this code to query ONLY the posts which belongs to **Portfolio Category**?
You can simply just add the `cat` or `category_name` parameter to your query. When using `cat`, you should use the **category ID** , and should you use `category_name`, it should be the **slug** of the category, not the name. Change <?php $tarali_query = new WP_Query('posts_per_page='.$nbmax.'&ignore_sticky_posts=1&paged='.$paged); ?> to <?php $tarali_query = new WP_Query('posts_per_page='.$nbmax.'&cat=CATID&ignore_sticky_posts=1&paged='.$paged); ?> For futher reading: `WP_Query`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, wp query, query posts" }
Clean way to initialize plugin in newly-added site when plugin has been network activated? I've been working on migrating one of my plugins to support multisite installs and am attempting to figure out the cleanest way to handle the following series of events: 1. Plugin is Network Activated 2. New site is added I'm currently listening to the activation hook which works for every other case, both individual activations and site-wide ones, but I'm not getting an activation hit when the new site is added. Incidentally, this strikes me as a bug in WP core... In any event, I need to catch this series of events and run activation things. I was looking at combining the wpmu_create_blog hook and is_plugin_active_for_network, but I'm not sure if there might _fingers crossed_ be a better way to do this.
After looking through Make WordPress, it looks like this is a known issue that won't be fixed due to scalability concerns with large networks. That same issue linked above recommends doing exactly the solution discussed above. Specifically, that would look something like this: public static function 145561_activate_new_blog($blog_id) { if (is_plugin_active_for_network(plugin_basename(__FILE__))) { // do activation for $blog_id } } add_action('wpmu_new_blog', '145561_activate_new_blog');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, multisite, activation" }
Information about Wordpress 4 Are there any details on when WP 4 will be released? Is it true it will be a fundamental re-write using considerable Ajax? I am really interested in the following issue which is reported as included in 4.0 <
Release Date: > WordPress 4.0 is planned for ~~August 27~~ September 3, 2014 > > Source WordPress 4.0 Release: > [...] For those unaware, for WordPress, version 4.0 sounds like a “big” version number but it’s just another major release for us, like 3.9 and 4.1, constructed over the same ~4-month release cycle. [...] > > Source For WordPress 4.0 features follow < Planned features at the moment: <
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "wordpress version" }
How to display dialog box to save file from wp_filesystem->put_contents function? I have this fragment: if(!$wp_filesystem->put_contents( $file_path, $file_content, FS_CHMOD_FILE )) { echo 'error during creating the file'; } This code works properly, but instead of saving the file on the server I would like to display browser dialog box to save the file with this content on local disk. Thanks in advance for any help.
> ... instead of saving the file on the server I would like to display browser dialog box to save the file with this content on local disk The answer is that that is not what the Filesystem API does. You are trying to, or hoping to, use it incorrectly. It doesn't work that way. The Filesystem API saves to the server filesystem, not to the client disk. The server does not have that kind of control over the browser or the client machine, and for good reason. What you will need to do is "ask" the browser to download-- something like this: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp filesystem" }
Using css class selectors on a specifc page I'm trying to position images next to several bullet lists in such a way the global default doesn't achieve so in my style.css file for the child theme I have my selector as .activities img{ code here; } then on the page I'm applying it to I find an img tag make it look like <img class="activities" src"linktoimage.png"/> When I refresh nothing happens to the image. I've tried using ID instead of class and putting the image within a DIV that uses the selector none of which has any effect. I'm possibly doing it wrong so any help would be appreciated thanks
This is off-topic, as it's a CSS question, not a WordPress question. That being said.. You need to attach your class to your tag. Use: img.activities { /* stuff here */ } Your current CSS selector targets this: <span class="activities"> <img src="image.png"/> </span>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css" }