INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
List custom post types in metabox Is there a function to list all custom post types in a metabox? I have wp_list_pages( $args ); to list the pages in metabox but now I need also to list all custom post types. Thanks for advices
<?php $args = array( 'public' => true, '_builtin' => false ); $output = 'names'; // names or objects, note names is the default $operator = 'and'; // 'and' or 'or' $post_types = get_post_types( $args, $output, $operator ); foreach ( $post_types as $post_type ) { echo '<p>' . $post_type . '</p>'; } ?> It will list of all public custom post types and you can read documentation on get_post_types here .
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, metabox" }
How can transfer get so large when exporting data (15-16MB to over 10GB) When I try to export a database throught **Wordpresses export-function** (database = about 15-16 MB), I get this in the xml-file created (that is 1kb): **Fatal error** : Allowed memory size of 100663296 bytes exhausted (tried to allocate 45481985 bytes) in row 2935 in functions.php. The limit of transfer is 10GB on the webhotel (space2u). But how could the transfer be so large? Line 2935 is inside a function that is hooked by: add_action( 'post_submitbox_misc_actions', array($object, 'callback-function') );
You seem to be confusing different things. I am not sure what precisely you mean by "transfer" (monthly bandwidth? disk space?), but 10GB figure likely isn't about _memory_ (RAM). Error you are getting _is_ about RAM. 100663296 bytes corresponds to just 100MB. That much is _typically_ enough for average WP install to function, but might not be enough for some specific functionality or third party code. I think the highest WP tries to request natively is 256 megabytes when manipulating images. You should inquire with your hosting about RAM available and configuring it to higher value. If that is highest you can get you might not be able to do resource–intensive operations.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "export, xml" }
How to get DEFER or ASYNC attribute to appear when I add a stylesheet with wp_enqueue_style from a plugin? Almost all of my CSS and JS resources can be postponed with an ASYNC or DEFER tag added to the resource. This may improve performance of my page load times considerably. However, I don't know how to specify these attributes to be added to the HEAD when wp_enqueue_style() takes care of adding them. It doesn't seem like wp_enqueue_script() takes a parameter for extra attributes. Is there another way?
As per WP Code Snippet blog, it looks like this is one way: Add this code snippet to your functions.php file. // add async and defer to javascripts function wcs_defer_javascripts ($url) { if (strpos($url, '.js') === FALSE) { return $url; } if (strpos($url, 'jquery.js')) { return $url; } return "$url' async onload='myinit()"; } add_filter('clean_url', 'wcs_defer_javascripts', 11, 1);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, css, javascript, performance" }
How to remove dashicons.min.css from frontend? Is there any way to remove the dashicons.min.css file from the frontend? I know that they are used by the admin panel, but my theme doesn't use them so it's an unnecessary request.
Try deregistering that stylesheet - add_action( 'wp_print_styles', 'my_deregister_styles', 100 ); function my_deregister_styles() { //wp_deregister_style( 'amethyst-dashicons-style' ); wp_deregister_style( 'dashicons' ); }
stackexchange-wordpress
{ "answer_score": 26, "question_score": 18, "tags": "theme development" }
Best way to modify a plugin with no hooks and no pluggable functions? I have to make some changes to some functions in a plugin that don't have hooks and aren't pluggable. My idea was to wrap the functions I modify in a `if ( ! function_exists())` and move my modifications into a separate plugin. Then whenever I need to update the plugin, I just re-add the `if ( ! function_exists())` wrapper. Please tell me why this is a bad idea and what I should be doing instead.
It seems like the plugin you are using are quite important to you and/or your client, and the plugin itself is most probably regulary updated with proper support. I would definitely contact the author and discuss possible changes to the plugin. If a change is a constructive change and would bring some degree of usefulness to the plugin, I see no reason why the author would not implement your changes in the near future releases/updates. Primarily, if your change is to out of scope of the current plugin, you can suggest and ask the author to just add a proper filter where needed in future releases/updates. But yes, I would start at the plugin author for such kind of support before looking into other solutions
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, pluggable" }
Creating a search with tag variable also added for more detailed results Wordpress search results is definately not the best indexing and search function we have seen.. If adding multiple tag variables in the search in order to get a more precise result work? For example: Default search query: `www.example.com/?s=kidsbook` What if we spiced it up a bit adding: in the search some more tags that the results must have (for example female author and bestseller). So that only post results of kidsbook AND from those results only the best sellers of female authors. would the bellow example work? www.example.com/?s=kidsbook&tag=femaleauthor&tag=bestseller Would the search accept both tags? Last question would this type of search cause a much greater load on the server? Thanks for your answers.
Add a new input to the form, the name is key, you can easily access query vars that match a paremeter supporter by WP_Query using the function `get_query_var`. For example, you could try to generate an URL like this: And with `get_query_var(tag)`, you get the values, and the you create a custom `WP_Query` using that parameters. $query = new WP_Query( array( 's' => get_query_var('s'), 'tag' => get_query_var('tag') ) ); One thing you have to take into account is that can't have the same parameter twice in the URL, well, you can, but you can't use the `get_query_var` function to get the value. You can use jQuery to get the selected options from a `select` element with the `multiple`attribute, and pass the selection to an input with the name "tag", there are other workarounds for this. The query wont affect performance that much. I hope this gives you and idea of what to do.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, search, tags" }
Auto-posting Facebook posts to blog Is there a plugin or programmatic way to automatically to take a Facebook account's posts, and automatically post it to a wordpress blog?
I've used this in the past: < You can see it in action here: < toward the bottom of the page on the left.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "blog" }
Adding Font Awesome to WP Plugin I'm trying to use font awesome icons for my plugin. I've read this page in the codex and this question. Here's what I've tried so far: I've added this on **_wp-plug-in.php_** (or should it be somewhere else?) > > add_action( 'wp_enqueue_scripts', 'wp_styles' ); > function wp_styles() { > wp_register_style( 'font-awesome', plugins_url( 'wp-plug-in/css/font-awesome.min.css' ) ); > wp_enqueue_style( 'font-awesome' ); > } > I'm hoping I could use it the usual way like: > `<i class="fa fa-twitter"></i>` But to no avail. It doesn't display anything at all. I know I'm missing out something and I'm hoping that someone could point it out and probably give me additional resources. Thank you. **UPDATE** It turned out the theme I had activated didn't have `<?php wp_head(); ?>` on the header. Lesson learned. :) Thanks a lot @Robert and @Abhik.
Did you create `wp-plug-in/wp-plug-in.php` file in plugins folder and added this following code. <?php /** * Plugin Name: Load FontAwesome * Version: 1.0 */ /* Exit if accessed directly */ if ( ! defined( 'ABSPATH' ) ) exit; function wp_styles() { wp_register_style( 'font-awesome', plugins_url( 'wp-plug-in/css/font-awesome.min.css' ) ); wp_enqueue_style( 'font-awesome' ); } add_action( 'wp_enqueue_scripts', 'wp_styles' ); And added font awesome css and fonts in wp-plug-in/css folder? And then activate this plugin from admin panel? Can you not see font-awesome.min.css file in website source code? Search for it?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, plugin development, wp enqueue style, wp register style" }
How to manage hundreds of WordPress sites? I am managing 100+ WordPress sites in a single multisite install. The sites are completely independent (i.e. the site's owners do not know that they are hosted on the same server). So far the multisite has served me well in maintainability (just one server to access to, one WordPress install, a single copy of each plugin, ...). There are problems, though: with multisite the user base is shared between all sites (it's a _network_ , after all), so that if a user sign up on a site, she can't sign up on another site with the same email; and I need the site admins to not know that they are inside a multisite. Is there a way to make the multisite user register with the same email on different sites? If not what's the best way to manage this use case? As an alternative I have thought of making multiple WordPress installations, symlinking the plugin folder (WP 3.9+) and using something like InfiniteWP to manage the sites.
There is a plugin for this: Join My Multisite > Allow site admins to automatically add existing users to their site, or let users decide at the click a button. I don't know how important it is to you that the users don't know that they are in a multisite but the list of the plugin's options is very interesting: > By activating this plugin, you give your Site Admins the following options: > > * Auto-add users > * Have a 'Join This Site' button in a widget > * Keep things exactly as they are > * Create a per site registration page > * Use a shortcode to put a 'join this site' button on any page/post. >
stackexchange-wordpress
{ "answer_score": 1, "question_score": 4, "tags": "multisite" }
Get all pages and posts with get_pages() or get_posts() Trying to get all posts (with all I mean all pages, posts and posts from custom post types). Is this possible? The documentation says I can only pass a string as `post_type` so how can I get all pages and custom post types? Example where custom post type is called `project` $args = array( 'exclude' => $inclPages, 'post_type' => 'pages,project', 'title_li' => __(''), 'sort_column' => 'menu_order' ); $pages = get_pages( $args ); Any advice would be appreciated
`get_pages` does not work with posts or post types that is not hierarchical like pages, so if your post type is hierarchical like posts, it would not work > This function can also retrieve other post types using the 'post_type' parameter, but the type must be hierarchical like pages, or the function will return false. If you need all post types to be returned, ie all `post`, `page` and custom post types, just pass `any` to `post_type` in either `get_posts` or `WP_Query`, the choice is up to you
stackexchange-wordpress
{ "answer_score": 6, "question_score": 0, "tags": "get posts" }
Get a custom field of all posts on current blog page I am trying to get a custom field value from all posts listed on current blog paginated page. Not sure if it's clear, let me explain it more. On blog index page (or on second page of pagination) I have 10 posts. And each post have a value for custom field **my-field**. So I want to list posts as it is but outside the post list (lets say in footer.php) I want to also list all the values of custom field **my-field** belonging to current posts. Not sure exactly how it can be done. **EDIT** To simplify (for understanding), I want to echo posts IDs of all listed posts in footer.php.
You could just rewind the query to loop through again: <?php rewind_posts(); ?> <?php while ( have_posts() ) : the_post(); ?> <p>Post Number: <?php the_ID(); ?></p> <?php endwhile; ?> THE LOOP
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "posts, custom field" }
How to query authors by custom taxonomy? I have a custom taxonomy for users which is country. Is there a way to query all admins by term_id or should I get all users and check each one with a for loop? I tried this: $user_query = new WP_User_Query( array ( 'role' => 'administrator', 'tax_query' => array(array('taxonomy' => 'country', 'field' => 'id', 'terms' => $country_id ) ) ) );
Not sure why you would try this with taxonomy. I would suggest making a meta_key "country" with the values. Then you can query it like in the documentation: $user_query = new WP_User_Query( array( 'meta_key' => 'country', 'meta_value' => 'Israel' ) ); Not sure why your taxonomy-query doesnt work, looks fine also, i use it like this for my post-types. How did you try? Maybe also post the function, where you register the taxonomy, where did you attach it to?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom taxonomy, users, user meta, advanced taxonomy queries" }
Add a field to the taxonomy editor? I would like to add an additional image field to WooCommerce Product Taxonomy Admin page as part of my theme. It works fine by modifying the existing class within the plugin, but it will be replaced when Woo Themes updates it. The class is included in class-wc-admin.php and then called directly from within the class-wc-admin-taxonomies.php file. I don't see any hook to modify the functionality. Any ideas on how to replace the existing WC_Admin_Taxonomies class without breaking when I upgrade? Screenshot of what I'm trying to accomplish: <
This is not Woocommerce specific, just the regular WordPress term edit screen. So you can use the normal action `{$taxonomyname}_edit_form_fields`. Example: add_action( "product_cat_edit_form_fields", function() { ?> <tr class="form-field"> <th scope="row">Additional image</th> <td>Some image upload code …</td> </tr> <?php }, 2000 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, taxonomy, woocommerce offtopic" }
Twenty Twelve entry meta data - change and move I'm trying to fix with the twenty twelve meta data. I've started fixing and successfully managed to get the date under the title of the post. Please visit my site to see. 1. One thing I want to do is to remove the footer meta data "This post was posted in..". And instead add: A."Comments: #number B. "Share this - with the icons inline with comments - Now we have it centered above the comments with the jetpack plugin. 2. Above the entry title i want do display which category the post is displayed in. So its displayed first with category, then title and last the time. 3. I also wants configure the time of the day in the time data. So it should be displayed like "16:45 | september 16, 2014"
If you don't want to use twentytwelve_entry_meta(); in the post loops that calls the date, category and adds that "This post was posted in" text itself, then you'll have to remove it and re-write from scratch. 1A: Comments and Number displayed, refer to the comments_number function: < <?php comments_number( 'No Comments', 'Comments: 1', 'Comments: %' ); ?> 1B: If this is coming from Jetpack, it will automatically place them for you. If you want to change where they appear, take a look at this topic: < 2: To show the current category(ies) that your post is in, refer to the the_category function: < 3: To change the format of the date, refer to the get_the_date function: < <?php echo get_the_date('G:i | F jS, Y'); ?> As well as the PHP manual for more date options: < Hope that helps!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post meta, theme twenty twelve" }
How to change menu URLs to hashes? I'm building a fullpage Wordpress site. Meaning the pages are not separate URLs, they are accessed through the same URL. Something like deuxhuithuit.com. So I have a menu that the admin creates by selecting different pages. Wordpress generates the unordered list of links with URLs like ` I want my theme to change those links into hashes to the same URL `< Any ideas?
Here's how I solved it so far. class themename_walker_nav_menu extends Walker_Nav_Menu { function start_el( &$output, $item, $depth, $args ) { $slug = get_post( $item->object_id )->post_name; $item->url = "#{$slug}"; return parent::start_el( $output, $item, $depth, $args ); } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "menus" }
How to get current page ID outside the loop? How to get current page ID outside the loop?
**Try** global $post; echo $post->ID; **or** (I don't know the difference) global $wp_query; echo $wp_query->post->ID;
stackexchange-wordpress
{ "answer_score": 82, "question_score": 56, "tags": "pages, id" }
Where to use $post global variable? I am confusing to use `$post` global variable. Is it use inside loop or outside loop? What is the advantage to use it inside and outside loop?
The `$post` global is set by `$wp_query->the_post()`. As `$post` is set by the main query and the fact that templates are set within the global variable scope, it is available throughout the template, so there is no need to explicitly calling the `$post` global when you are within the specified template as the `WP_Post` objects can be accessed any where. You can access the `WP_Post` objects by just simply calling them directly, for example `$post->ID` to retrieve the page ID on a page template When you need to access post data outside of a template, for example, in a function or in a widget, you need to call the `$post` global to make the post data available for use.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "wp query" }
Redirect after user changes password I'm doing a custom form where the user can change is password. After submission and if the password is according to the rules I save the new one, overriding the old one, to the database, delete the cache and do the logout and signon of the user. Right now after that it's redirecting do the homepage, but what I want to do after is to redirect the user to a specific page, where I show a message, instead of going to the homepage. Can anyone help me with this? Thank you!
As you said you have a custom form, I am assuming you are not going to use WordPress default 'reset password' functionality. You can use wp_redirect or wp_safe_redirect to redirect to a specific page after a particular condition (e.g. if the password is changed successfully)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect, login, password" }
Serializing User Role for update_user_meta I've created a custom user role and am attempting to change the users role from CUSTOMER to ADVOCATE on purchase of a particular product (using WooCommerce). I'm really close but struggling to get the correctly serialized data into my table: $order = new WC_Order( $order_id ); $items = $order->get_items(); $new_role = 'Array([advocate] => 1)'; $data = serialize( $new_role ); if ( $product_id == '786' ) { update_user_meta( $order->user_id, 'wp_capabilities', $data ); } The correct table is being populated at the correct time but as s:30:"s:22:"Array([advocate] => 1)";"; rather than what I need it to be which is a:1:{s:8:"advocate";b:1;} Where is my serialization tripping up?
I think you are not handling the array part correctly. The right syntax is - $new_role = array("advocate" => 1); The syntax that you have used is shown when you print some array on your screen but it should be written in above format in your PHP code. Currently, you are capturing it as a string and not an array.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "user meta, woocommerce offtopic" }
Add line breaks in Category description via enter My client wants to ad line breaks in category description via keyboard enter. In the editor the white space is added, but it is not shown on the website. I can add it with `&nbsp;` but I have to be able to do it by enter key. I tried commenting out this in `default-filters.php`: foreach ( array( 'pre_term_description', 'pre_link_description', 'pre_link_notes', 'pre_user_description' ) as $filter ) { add_filter( $filter, 'wp_filter_kses' ); } But it didn't work. Neither adding this to my `functions.php`: $filters = array('pre_term_description', 'pre_link_description', 'pre_link_notes', 'pre_user_description'); foreach ( $filters as $filter ) { remove_filter($filter, 'wp_filter_kses'); } Thanks!
You can use the standard PHP function nl2br for that echo nl2br(category_description( $category_id ));
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "categories" }
Lowest catagory link I am trying to display lowest child category link.At this point I can only display the child category name but I want it with permalink.So far my approach $categories = get_the_category($post->ID); foreach($categories as $category) : $children = get_categories( array ('parent' => $category->term_id )); $has_children = count($children); if ( $has_children == 0 ) { echo $category->name; } endforeach; It display the lowest category name but not with hyperlink to that category. How can I link the category?
Atlast done it fully $categories = get_the_category($post->ID); foreach($categories as $category) : $children = get_categories( array ('parent' => $category->term_id )); $category_link = get_category_link($children); $has_children = count($children); if ( $has_children == 0 ) { $name=$category->name; $category_link = get_category_link($category); echo "<a href='$category_link'>$name</a>"; } endforeach;
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, theme development" }
How do I 'rebuild' the WordPress Media library after transfer to new host? I recently inherited a large site from a developer that vanished. The site has more than 6,000 images. In the pages most of the images are missing, however, they are referenced in the media library and I can see them on the server under wp-content/uploads. When I try to access any of these images with the blank thumbnail I get the following error message: > Missing Attachment Given that this site has been moved to a new host I am pretty sure that these images are not properly referenced but I am not sure how to modify the path to the images to get them to show up properly. I did some research and tried the following: UPDATE wp_posts set post_content=REPLACE(post_content, 'mysitexyz.net.basepointsite.com/', 'mysitexyz.net/'); What is the correct way to re-associate these images and have them appear correctly in the media library?
There's a few plugins to fix this, but basically it your database still references the images to be "oldsite.com/wp-content/uploads/" and you need it to be "newsite.com/wp-content/uploads" So you have to change all old references. You could use SQL: UPDATE wp_options SET option_value = replace(option_value, ‘ ‘ WHERE option_name = ‘home’ OR option_name = ‘siteurl'; UPDATE wp_posts SET guid = replace(guid, ‘ UPDATE wp_posts SET post_content = replace(post_content, ‘ ‘ UPDATE wp_postmeta SET meta_value = replace(meta_value, ‘ ‘ I used to use this plugin which worked great for transferring sites. < And this plugin is specifically for letting you sync local and remote changes that have been made throuh ftp: < Or here's a few other popular ones, they pretty much do the same thing: MPress Fix URL References < Go Live Update URLS <
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "media library, paths" }
Update meta_key value for a page I have inherited a WP site where some home page slides are pulled using <?php $po = get_posts( array('post_type' => 'page', 'meta_key' => 'Home Slide', 'order' => 'ASC', 'orderby' => 'menu_order', 'posts_per_page' => 5 ) ); ?> The site owners want these slides changed but the Home Slide meta_key is not exposed in the UI. I tried passing this to add a page (via the home page template). <?php update_post_meta( 135, 'meta_key', 'Home Slide' ); ?> And this to remove a page <?php update_post_meta( 146, 'meta_key', '', 'Home Slide' ); ?> But this did not appear to have any effect. What is the correct way to either expose this in the UI or make changes/additions to it? Also- these are sorted on menu_order. Does that mean that, as they are now, I need to re-order them in the site menu in order to change their order?
Go to the Page editor. Click the "Screen Options" box in the top right corner. In the dropdown, turn on the "Custom Fields" option. Now scroll down below the post editor area. Edit the fields as needed.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "sort, post meta" }
Deregister CSS style link 'open-sans-css' When user is logged in WP add in its footer this CSS: <link rel='stylesheet' id='open-sans-css' href='//fonts.googleapis.com/css?family=Open+Sans....' type='text/css' media='all' /> That style is not registered inside my theme, if I change my theme I still have that file called in any theme, it is somewhere inside WP core files. How to remove it?
WP Core actually uses Open Sans font; it's not a plugin. there is a plugin that removes it, but you can probably simply dequeue or deregister it. adding this to functions.php should work; if you want it removed from the backend as well, hook into the `admin_print_styles` action. function dequeue_opensans_css() { wp_dequeue_style( 'open-sans' ); } add_action( 'wp_enqueue_scripts', 'dequeue_opensans_css', 999 ); if it's in the footer, change the `add_action()` line: `add_action('wp_footer','dequeue _opensans_css',1);` untested, but that should work.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "css, admin bar, wp head, admin css" }
How to save information related to post in database? I created a post-to-email plugin and I need to save something in the database when the post is sent so I don't allow users to send it twice. How do I save this in the database? And how can I retrieve it later?
How about post meta ? if ( ! update_post_meta (7, 'sent', '1') ) { add_post_meta(7, 'sent', '1', true ); }; add_post_meta Or options table or custom table
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, php, database" }
How to mass-delete inline styles in Wordpress custom post type automatically? I'm looking for a pragmatic way to delete about 100+ individual pages worth of inline styles. I had entered in content for a client by copying and pasting from Word, which took all that data with it and wrapped it in inline styles. It doesn't make sense to go through each post individually. Has anyone done this before? I would be fine with any solution that 'works.' Myself and my employer thank you for any input immensely.
I would use the Search Regex plugin. It will allow you to use a regular expression to find and replace (in your case _delete_ ) inline styles. Make sure you backup your database before you begin! A simple regular expression that should work for you would be (style=").*" It will look for a string starting with `style="` and containing any number of characters until it hits another double quote `"`. (That would be an inline style applied to an HTML element). You'll "replace" it with an empty value (to delete it). You can also test your content / regular expression with Regexr to ensure the one I gave you will work. **Backup your database** before you begin. If something goes wrong you can restore it. It looks like this plugin will allow you to Search (as a test) before you run a Replace & Save.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "functions, customization" }
Debugging a redirect loop affecting only certain pages I am trying to fix a site which has several redirects that seem to have been added via a plugin called Peters plugin redirect. The plugin has since been deactivated and delated but the redirects loop is stil present. I have tried the following: * deactivating and deleting the plugin * refreshing the permalinks * clearing and resetting the htaccess defining the home and site url in wp-config * deleting the rewrite rules in the options table No caching plugin is being used and the problem remains in Private browsing mode. The only two pages affected are the home page and the registration page. I would appreciate any ideas on how to resolve this or any suggestions on how to go about debugging. EDIT: I found this which might have something to do with the issue as the site owner likes to use capital letters.
Turned out to be cacheing problem. WP Super Cache had been installed and deleted(uninstalled -perhaps incorrectly) but the advanced-cache.php file remained in wp-content.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect, htaccess" }
How to change home page only in WordPress I am a newbie in WordPress theme development. I have a WordPress site on online. I create a new home page for my wp site and I want to use it my wp site instead of old home page. And I want that the other pages would stay same as before. In that case, what should I do? Please share the details information. And if anybody knows good tutorial about changing home page only, please feel free to share it. Thank you. N.B. In that case, may I create child theme?
You should use custom template for this purpose. Create a new file homepage.php and write the below code. <?php /* Template Name: Homepage */ ?> <?php <!--Your code goes here--> ?> Then, create a new page in admin panel like HOME and in right sidebar select your "homepage" template you just created. Do not forget answer given by WisdmLabs. You will also have to follow those answer.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp admin, homepage" }
add_rewrite_rule on multisite doesn't work I define a rewrite rule on an init hook like: add_rewrite_rule( 'foobar/(abc|def|ghi)/(.+)(/(\d.+))', 'index.php?my_action=$matches[1]&my_name=$matches[2]&my_version=$matches[4]', 'top'); This works with following URL on a single WP installation: However it doesn't on a multisite installation. It seems there's problem with rewrite rules on multisite an there's ticket #19896 which describes a similar problem on "non WP rules" I have no idea what I should add to the `.htaccess` file and I prefer a "proper" solution. **EDIT:** I have forget something important: I'm using WordPress MU Domain Mapping to use different domains and while the network is on `network.example.com` the site I use `add_rewrite_rule` is sub.example.com
It seems the problem is not with `add_rewrite_rule` rather with the `.htaccess`file for the multi site. One of the test addresses was Here's a part of the htaccess which causes the result (Line 2) RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L] RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L] RewriteRule . index.php [L] If I comment this line out it works as expected but it may break other thing. So you have to add your own rule **above** the latest block: RewriteRule ^([_0-9a-zA-Z-]+/)?foobar/(abc|def|ghi)/(.+)(/(\d.+))$ index.php?my_action=$2&my_name=$3&my_version=$5 [R=301,L]
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "multisite, htaccess, rewrite rules" }
How to Determine a Post's Last Edited Date? I'm writing a little extract script to do a DB pull. I've been asked to get all restaurant posts (custom post type) that are among the 1000 top hit, OR have been added or edited in the last 3 years. OK, so I've got the 1000 top hits done through an export from Google Analytics. Then I did a SQL extract like so: SELECT p.ID, concat(' p.post_name) FROM wp_posts p WHERE p.post_type = 'restaurant' AND p.post_status = 'publish' AND p.post_modified < DATE_SUB(now(), INTERVAL 36 MONTH); I thought I had it licked. Then the users looked at it, and found some restaurants that I thought were outside the 3 yrs, which were in fact _inside_. On investigation, I found it was due to **revisions**. :( So, what is the best practice for determining last edited date, taking into account revisions?
If I got your question right, and you want posts created/modified between 3 years ago and today, try this query: SELECT p.ID, concat(' p.post_name) FROM wp_posts p WHERE p.post_type = 'restaurant' AND p.post_status = 'publish' AND p.post_modified > DATE_SUB(now(), INTERVAL 36 MONTH); Because your `DATE_SUB` returns something like this: NOW - 3 years, so, it's something along the lines of `2011-09-20 12:21:41.000000`, and you are using a `<` sign, so you are checking for post that were created or modified before that date, so instead of getting the post created/modified between 3 years ago and today, you are getting the post created/modified more than 3 years ago. Also, you aren't getting revision, because as you specify the `post_type = 'restaurant'`, and revision have a `post_type` called `revision`, you are just getting the post that belong to the custom post type you specified.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, revisions" }
How to fix Sign In option in WordPress I have a WordPress site with “Sign In”option right side top: < I want that when login in my WordPress site the then display a “Log Out” option only and “Sign In” would be disappeared like this: < This is my code: <div class="fix floatleft sign_in"> <a href=" In</a> <a href=" amp;redirect_to=http%3A%2F%2Fwww.chicago-plastic-surgeons.com&amp;_wpnonce=6049e0b736">Log out</a> </div> How could I fix it? Thank you. N.B. Recently I have changed my site home page. So, I have already created and customized wp-login.php file in WordPress directory. I just want to use link form there which I mentioned in my code.
It's relatively simple to achieve that, you need to use the `is_user_logged_in()` function, as follows: <div class="fix floatleft sign_in"> <?php if(is_user_logged_in()) : ?> <a href=" out</a> <?php else : ?> <a href=" In</a> <?php endif; ?> </div> The code asks whether the current user is logged in, and if they are show the log out button, if they're not logged in, it will show the log in button. You can find out more information about the `is_user_logged_in` function on the WordPress Codex.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp login form, wp signup" }
What is _transient_random_seed for? This is a very short question. `_transient_random_seed` is in `wp_options`. What is it for?
The wp_rand function mixes up the randomization of random numbers with various means, and in between runs it stores the random seed so as to keep the shuffling going every run. The random_seed transient is where it stores that.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wpdb, options" }
Stop Wordpress processing Javascript as text I'm currently developing a bus route planner, using Wordpress as my CMS. I've added some JQuery code to add support for ajax (so visitors can use the route planner and load the route without having to go to another page), but it's not working. On closer inspection using Chrome's Inspect Element, Wordpress appears to be adding paragraphs to the Javascript code, although the Javascript code is properly configured and is recognised as such: !enter image description here Another member on the project also has the same issue: !enter image description here Why is Wordpress doing this, and how can I stop Wordpress from adding paragraphs to the code? I am adding the code through the raw text editor for the page, so it's not like I'm adding the code via the Visual mode.
The post editor is really not meant for inserting functional code like JavaScript into the page. Anything you put through the post editor will get run through `wpautop()` before output, which is what adds the paragraph tags -- even if you enter it via the Text mode. I'd suggest outputting your JavaScript via a hook on the page instead of via the post editor. Something like this: /** * Output JS to the page head. */ function output_head_js() { ?> <script type=“text/javascript”> $( ‘#gosearch’ ).click( function() { … }); </script> <?php } add_action( 'wp_head', 'output_head_js' );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "plugins, jquery" }
Fetch posts from current week (Sunday to Saturday) I'm trying to fetch posts from current week. <?php $args = array( 'date_query' => array( array( 'year' => date( 'Y' ), 'week' => date( 'W' ), ), ), 'post_type' => 'stars', 'posts_per_page' => 99, 'order' => 'DEC', ); $loop = new WP_Query( $args ); ?> This code is fetching the posts from **Monday to Sunday** (Start day of my week is "Monday" in general settings.) But when I changed the start date of week to " **Sunday** " in the general settings, the above code is not fetching any posts. I referred to this codex and it leads me to this MySQL function. But I'm not sure how to implement that in my query. Any ideas?
You can try: 'date_query' => array( array( 'year' => date( 'Y' ), 'week' => strftime( '%U' ), ), ), where `%U` is: > Week number of the given year, starting with the first Sunday as the first week or 'date_query' => array( array( 'after' => strtotime( 'last Sunday' ), ), ),
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "posts, wp query, date" }
Get taxonomy names by post id I'm trying to create a single page where I display a few posts on one page. So far so good. Works all fine. Now I display posts in a foreach loop where I check if they are connnected to the page. What I need ist something like `wp_get_post_terms($post->ID);` but that doens't work. There are `custom registered_taxonomy`'s. So how can I get all `taxonomy names` by `$post->ID`?
Ooh, thank's for the advices and help (Robert + Peter). The Term confused myself :) This worked for me: $taxonomies=get_taxonomies('','names'); wp_get_post_terms($post->ID, $taxonomies, array("fields" => "names"));
stackexchange-wordpress
{ "answer_score": 9, "question_score": 8, "tags": "custom taxonomy, taxonomy" }
Hide a Menu Item on Login I am using the following code to hide a menu item when a customer is not logged and show it when a customer is logged in. .hide-item-not-login{ display: none !important; } .logged-in .hide-item-not-login{ display: block !important; } I applied the class `hide-item-not-login` to my menu item and it works fine. What I actually want is the opposite. I want the menu item to hide when user logs in and show up when the user (cutsomer in woocommerce) is not logged in. What changes are suggested? Any help is highly appreciated.
Can't you change CSS rules? .hide-item-not-login{ display: block !important; } .logged-in .hide-item-not-login{ display: none !important; } **EDIT** To add login/logout menu item, you will need to add one more class to logout menu item. Let's say you added class `.logout-link` to logout menu item. Then you can add css like this. .hide-item-not-login{ display: block !important; } .logged-in .hide-item-not-login{ display: none !important; } .logout-link{ display: none !important; } .logged-in .logout-link{ display: block !important; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, menus, css, woocommerce offtopic" }
Custom Fields Bulk Edit I have a question. I am running detube theme which has a custom field named "dp_video_code" in which i put my video embeded code. Recently the embeded code has change and I need to modify the video code in all posts(I need to replace the text "preview" from the code with "edit"). Is there anyway to do this without take all posts one by one? Can I be done with a sql query? If yes what would that be? I saw some plugins like "Custom Field Bulk edit" but it isn't what I search. This is how the custom field looks: !I need to replace the "preview" with "edit" in all posts Thanks!
**FIRST BACKUP!!!!!** **NEXT, BE SURE THE BACKUP IS RIGHT** Now, you can use this code in PHPMyAdmin UPDATE wp_postmeta SET meta_value = REPLACE(meta_value, 'preview', 'edit') WHERE meta_key = 'dp_video_code' Make sure that's the correct name of the custom field, you can check it in the `wp_postmeta` table.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, customization, sql, bulk" }
Exclude categories from search query I have two categories that I want to exclude from my search results, so far without luck. I have tried adding the following piece of code but it didn't work. $search_query = query_posts(array('category__in' => array(-22, -21))); Here is my current code. global $query_string; $query_args = explode("&", $query_string); $search_query = array(); foreach($query_args as $key => $string) { $query_split = explode("=", $string); $search_query[$query_split[0]] = urldecode($query_split[1]); } // foreach $searchq = new WP_Query($search_query); while ($searchq->have_posts()) : $searchq->the_post();
You can use pre_get_posts action to exclude categories from search query. function wcs_exclude_category_search( $query ) { if ( is_admin() || ! $query->is_main_query() ) return; if ( $query->is_search ) { $query->set( 'cat', '-22, -21' ); } } add_action( 'pre_get_posts', 'wcs_exclude_category_search', 1 ); You should paste this code in your theme's functions.php file.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "categories, wp query, search" }
What is the earliest hook to modify post content? I have installed a plugin that adds stuff at the end of the content. I just want to apply my modifications to the post content before this plugin does. In my case or otherwise, what is the earliest hook that can be used to modify post content even before `the_content` filters are applied?
When two or more filters are hooked to the same filter hook, the conflict is resolved as follows: 1. If the filters are hooked with a `priority` parameter, the filter with a lowest value for the priority will be executed first. If no priority value is supplied, the default value is taken as 10. 2. If two or more filters are hooked with the same priority, the filter that was hooked first will take priority. Eg. add_filter('the_content','filter_1',5); add_filter('the_content','filter_2'); add_filter('the_content','filter_3'); add_filter('the_content','filter_4',1); In the above example, `filter_4()` will be called first, followed by `filter_1()`. `filter_2()` and `filter_3()` have same priority ie. 10. Hence, `filter_2()` will be called next because sequentially, `filter_2()` was added before `filter_3()`. And of course, finally `filter_3` is called. Reference: Wordpress Codex Page.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "filters, the content" }
Color Picker - Theme options I've been creating a Theme off my own back just teaching myself about the in's and out's of wordpress API. Firstly this place has been of great use to me! Now for the question, recently just incorporated the WordPress color-picker into my theme options and i'm wondering if there is a way to manipulate the colour output to effect certain bits of CSS. For example. I use my color picker option in theme options to change the color of the site title. I'd just like to know where exactly the output for the color goes and how it effect that certain piece of CSS.
Here is a great tutorial on how to add a colorpicker to your admin page. Regardless of how you are adding a colorbox or what plugin you are using, assuming you added it by adding a field in your options table (as provided in the link), you can use the color value anywhere in your template files with a call to `get_option`: $options = get_option( 'my-theme-options' ); $bg = $options['background']; For example, as mentioned here, to colorize your first level headings add the call in your `wp_head` section. function my_wp_head() { $options = get_option( 'my-theme-options' ); $color = $options['color']; echo "<style> h1 { color: $color; } </style>"; } add_action( 'wp_head', 'my_wp_head' ); Make sure you validate and escape appropriately when handling user inputs.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, color picker" }
how to create plugin single licence only I have a question how to create activation key ? I want to build a premium plugin but don't know how to make it for single license only, there are any way to do this ? any solution ?
I do so, using an licence Server. The Plugin / The Theme sends an licence-code (md5 on the wordpress-url) each hour to that Server and check whether the licence-code is valid or not (also get some remote Settings, if you have multi-mode-licences (Basic, Standard, Extended) or so) and if it's not valid, the plugin stops working / the theme just Displays an maintenence-page. May this is an way for you to do what you are planing to do.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "licensing" }
get_posts() using an array of post ids There's an array of post ids, and I'd like to use it to load these particular posts. I'm using get_posts() but there's some kind of problem using an array for 'post__in' argument. Here are the contents of the array: Array ( [0] => 44376 [1] => 44371 [2] => 44387 [3] => 44395 [4] => 44334 ) And here's the PHP code: $args = array( 'post__in' => $post_ids; ); $posts = get_posts($args); I tried using explode() to convert the array but didn't work. Any suggestions?
Please try this instead: $args = array( 'post__in' => $post_ids, ); $posts = get_posts( $args ); **Lesson learned** : _Always check your PHP scripting errors!_ ;-) Check for example this Codex page on debugging.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "get posts, array" }
Caching & Outputting RSS Data I need to pull in 2 different RSS feeds from an external site into our site. I have two questions about how to best do this: 1. I want to cache the feed so that it doesn't get pulled in every time someone visits the site. What is the best way to go about doing that in WordPress? 2. I will need to output the data (post title and thumbnail image) for each post. What is the best way to go about doing that in WordPress? Thanks for your help!
I think you're looking for the core function fetch_feed(), your new best friend! From the Codex: > Retrieves an external feed and parses it. Uses the SimplePie and FeedCache functionality for retrieval and parsing and automatic caching. and > `fetch_feed` caches results for 12 hours by default. You can modify this by modifying the time interval via the filter `wp_feed_cache_transient_lifetime`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "rss, cache" }
Conditional for 404 page not work I am trying to add a conditional to enqueue script only for 404 page. Theoretically I would have to use is_404() right? Well it does not work: if ( is_page_template('404.php') ) { add_action('wp_enqueue_scripts', 'scripts_404'); } if ( is_404() ) { add_action('wp_enqueue_scripts', 'scripts_404'); } nor does the is_page_template work. However if I add this line without conditionals, it works just fine. Any ideas or am I missing something? Thanks in advance.
You should wrap your enqueue/register function in your conditional, not your `add_action()` You can try something like this using the `is_404()` conditional check function enqueue_404_script() { if(is_404()) { //do what you need to do } } add_action( 'wp_enqueue_scripts', 'enqueue_404_script' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "404 error, conditional content" }
Shortcodes (with a space) added to php Sample I have found only a small handful of posts from around the internet regarding Shortcodes and allowing them to work / execute within Admin Pages. So, I have made several admin pages in Wordpress, and one of them requires me to add a shortcode from one of the other plugins. I have found this solution which according to the comments _it works_ : do_shortcode() within Admin Page However, the example in the answer uses _[example]_ as the shortcode, the shortcode I am trying to use is _[customcont form=3]_ If you notice, there is a space in my shortcode which is what puzzled me. _Because of that I'm now struggling how to incorporate that into the example that is on that thread??_ This is not a duplicate question, I'm asking how to add my shortcode with a space into the example provided. Thank you in advance!
there isn't an "space" in the Shortcode-Name. What you have, is an shortcode called "customcont", that is providing an Parameter called "form". So this is, how it should work: function example_shortcode( $atts = array(), $content = '' ) { extract( shortcode_atts( array ( 'form' => 0, ), $atts ) ); return 'FORM TO DISPLAY IS #'.$form; } add_shortcode( 'customcont', 'example_shortcode' ); With the `$form` Variable you can Access the Number of the form to Display, in your case the "3".
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, shortcode, admin" }
Admin auto-refresh is interfering with Firebug -- how to prevent it? I'm developing a plugin that adds a metabox to the post editing page. When I try to debug it with Firebug, about every 15 seconds the Firebug display refreshes as though the page has reloaded. This collapses the code tree and loses my place, so I have to start from scratch... and get where I want within 15 seconds. I've disabled all plugins, so I assume this is standard WordPress behavior (version 4.0). Is it possible to prevent this auto-refresh, or to otherwise make Firebug usable on the post editing page?
Per comments, an alternative is to use the built-in Firefox debugger instead (Inspect Element (Q)) - it's very good (now) and is (almost completely) unaffected by the WP heartbeat.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugin development, admin, metabox" }
How to perform WordPress backups using wp-cli? I am relatively new to working with WordPress, but I am very comfortable with, and prefer to use the command line. I need to backup WordPress before performing a version upgrade. I came across wp-cli and I assume that it is the go-to utility for working with WordPress on the command line. When working with WordPress, what do I need to back up, and how can I do this from the command line? Bonus question: how would you go about automating this to perform regular backups?
You can use the WP-CLI command `wp db export <filename>` Run the command from within the home directory for the install. Now, you have a database included in your files. Zip up the directory and move it aside. Now you can perform the upgrade, and if something breaks, replace with the old site and import the old database. voila, previously working site restored.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "backup, wp cli" }
apply_filters() function I have used **apply_filters()** while retrieving the content from WordPress post like: $content=$query_val->post_content; $content = apply_filters( 'the_content', $content ); When I was using **_apply_filters()_** the **_apostrophe( ' )_** in my text shows some characters.After I have removed **_apply_filters()_** it shows properly. So please explain it clearly!! What it is doing? I have referred this link Referal_link, but I'm not clearly understand.
If the characters are html entities like &nbsp &lt or &#60 then use php's default html_entity_decode() function to get the content in proper text format.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions" }
How to add img into a plugin? I started constructing my first Wordpress plugin but got an issue... I've a folder-file structure like that: * PluginFolder/ * TemplateFolder/ * img/ * my files php How can I use the /img/ folder in my plugin? I tried the URL with but didn't works form me. I don't know whether it is necessary to use any WordPress-specific function, like the bloginfo('template_url') or so. Any help would be greatly appreciated!
<?php echo '<img src="' . plugins_url( 'img/image.png', __FILE__ ) . '" > '; ?> here is the link how to add images or any other files from plugin folder <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development" }
Pulling posts into static site (wordpress as subdirectory) I’m currently redeveloping a site, and in the desire to keep everything as lightweight as possible, I’m developing it outside of WordPress and will only be using WP for the blog portion of the site. I’ve basically got a directory structure like: /_resources index.php /about/ /services/ /blog/ /wp-admin /wp-content etc I’m looking to create a “recent posts” feature on the homepage, and am wondering if there is a way to pull the post data out of WordPress and into my ‘out-of-WordPress-context’ pages. Any insight is greatly appreciated.
There are several ways to do it: 1. SQL query to the wp database 2. Using a Restfull API plugin: < you will get the json of the posts. 3. Using the RSS Feed (check this tutorial < To be very light you can cache the results will all options. You can grab the results and cache that results for X hours/days depending on your new posts frequency. So it will only make the request to one of the ways above when cache time as expired. Cheers
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization" }
Changing a post status name How do I change the status name "Trash" to "Archive". I don't want to change the functionality of the status or make a new status. I have tried Edit Flow custom status but I get some conflicts with another plugin and it seems a bit of a bulky solution for the small change I want to make. It must be possible to just change the status name "Trash" to "Archive"? I have looked through the WP admin files but I cant find any leads, maybe I am missing something. Thank you in advance.
Found this nice little bit of code from < add_filter( 'gettext', 'wps_translate_words_array' ); add_filter( 'ngettext', 'wps_translate_words_array' ); function wps_translate_words_array( $translated ) { $words = array( // 'word to translate' = > 'translation' 'Posts' => 'Article', 'Post' => 'Articles', 'Pages' => 'Stuffing', 'Media' => 'Upload Images', 'Links' => 'Blog Roll', ); $translated = str_ireplace( array_keys($words), $words, $translated ); return $translated; } Add this to functions.php and change accordingly, although in saying that I have a custom plugin where I add things like this as it deactivates if I make a mistake, rather than functions.php which seems to break the website.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post status, trash" }
Post thumbnail height problem I am trying to create a square thumbnail with auto crop with size of 300px 300px. I only get the width of 300px but the height is auto, i think is not cropping. I tried this: add_image_size( 'custom_image_size', 300, 300, true ); the_post_thumbnail('custom_image_size'); and this set_post_thumbnail_size( 300, 300, true ); the_post_thumbnail(); but i get the width 300px and the height is auto. I also tried to Regenerate Thumbnails by using a wordpress plugin. So what should i do to get the thumbnail 300px with 300px ? Images have dimensions: 1600 × 1200... so the images are bigger then 300px in width and height.
So i followed this link how-to-get-larger-images-in-a-wordpress-gallery and i changed the Thumbnail size to 300px with 300px from SETTINGS -> MEDIA, and then run a Regenerate Thumbnails. Now the thumbnails are ok by using the code <?php the_post_thumbnail( array(300,300) ); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, post thumbnails, images, cropping" }
PHP error in shortcode Can anyone help me see the error in this code? I'm trying to implement a function via shortcode which I found here: <?php if (function_exists(‘wooslider’)) echo do_shortcode(‘[wooslider slider_type="posts" limit="3" link_title="true" layout="text-bottom" overlay="full" category="homepage-feature-post"]‘); ?>
You are not using proper syntax, so you are likely getting a syntax error. You are using some strange sign in your code where you should be using a single quote (`'`). Also, use curly brackets to enclose a condition. It is easier to debug <?php if(function_exists('wooslider')){ echo do_shortcode('[wooslider slider_type="posts" limit="3" link_title="true" layout="text-bottom" overlay="full" category="homepage-feature-post"]'); } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "functions, shortcode" }
If logged in user meta is I was wondering if it's possible to display certain content _if_ a user meta field is set to a certain value. The most related thing I could find is get user meta, however it seems to get the user meta from the author of the page/post, and not from the logged in user - correct? Appreciate any hints - cheers!
No, not correct - `get_user_meta()` returns meta data based on the `$user_id` parameter you provide. You can combine it with `get_current_user_id()` to check if an user is logged in and than - if so - get the post meta. E.g. like this: $curr_user_id = get_current_user_id(); // the value is 0 if the user isn't logged-in if ( $curr_user_id != 0 ) { // we know now the user is logged-in, so we can use his/her ID to get the user meta $um_value = get_user_meta( $curr_user_id, 'your-key', true ); // now we check if the value is correct if ( ! empty( $um_value ) && $um_value == 'your-value' ) { // if so we can output something echo 'user meta has the value'; } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "user meta" }
User Selectable Delete of Pages in my WP MultiUser project i am designing a template for deleting a page from the front-end (only the super admin can access the back-end admin panel) I have almost achieved the desired result, but when I press "Delete," the function deletes all pages. I just want to delete only the selected page. Here is the code that I created: <?php $pages = get_pages(); foreach ( $pages as $page ) { $option = '<li>'; $option .= '<a href="' . wp_delete_post( $page->ID ) . '">'; $option .= $page->post_title; $option .= '</a>'; $option .= '</li>'; echo $option; } ?> edit 2 Sorry i miss few changes <?php $pages = get_pages();foreach ( $pages as $page ) { $option = '<li>'; $option .= $page->post_title; // $option .= '<a href="' . wp_delete_post( $page->ID ) . '">'; $option .= 'Delete</a>'; $option .= '</li>'; echo $option; } ?>
You are deleting all pages with that code because you are triggering the function wp_delete_post(). You should build the url to delete the page(or post) like this: $delLink = wp_nonce_url( get_bloginfo('wpurl') . "/wp-admin/post.php?action=delete&post=" . $page->ID, 'delete-post_' . $page->ID); So your code should be: $pages = get_pages(); foreach ( $pages as $page ) { $delLink = wp_nonce_url( get_bloginfo('wpurl') . "/wp-admin/post.php?action=delete&post=" . $page->ID, 'delete-post_' . $page->ID); $option = '<li>'; $option .= '<a href="' . $delLink . '">'; $option .= $page->post_title; $option .= '</a>'; $option .= '</li>'; echo $option; } Cheers
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "posts, pages" }
How does WordPress generate a comment website preview? In the WordPress comment que, hovering over the URL of a comment generates a preview of the website. How does WordPress handle this and does this generate a hit, or 'visit' to that website?
WordPress runs a service to generate screenshots. You can get any website screenshot like this. And yes, it records as a hit on website and will be logged.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "comments" }
If is page, archive or search output this code Hi there I'm trying to make this code works for more than just home page but I'm getting errors while trying to accomplish it... can someone help me? I'm trying to use this: <?php if (is_front_page()) {?> <div>Flash Gordon</div> <?php } ?> But I want to use more just only is_front_page like, if `is_front_page` or`is_archive` or if `is_search` as well. Ho can I do this?
You can add `OR` conditions like this. <?php if ( is_front_page() || is_archive() || is_search() ) {?> <div>Flash Gordon</div> <?php } ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, pages" }
Admin Message Broadcast for all wp users Wordpress admin sends a message and it will be shown in frontend to registered wp users. Read and unread facility is also required Any Plugin suggested for this task?
Use this Plugin to achieve what you want.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins" }
How To Make Connection To WordPress Data Base In A Plugin? I am learning Plugins and I am trying to connect WordPress database `wp-config.php` in my Plugin PHP code. Currently for checking my code, I used the below connection and it is working fine. Now I converted it into a WordPress plugin so anyone can use this but now its time to make WordPress database connection. //Connection To DataBase $host = "XXXXXXXXXXXXXX"; $username = "XXXXXXXXXX"; $password = "XXXXXXXXXX"; $dbname = "XXXXXXXXXXXX"; $connection = mysql_connect($host, $username, $password); mysql_select_db($dbname); So How to insert `wp-config.php` like something `require_once(wp-config.php');` in plugin instead of above code to make WordPress SQL database connection in my plugin file?
I found the answer my self. First open your `wp-config.php` and check the bottom of file that Is that contain the below code?... if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); If yes then add the below code to make the connection in your plugin PHP files to connect with `wp-config.php` file that contain Database Name, Database UserName, Database Password, Database Host... ... require_once(ABSPATH . 'wp-config.php'); $connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD); mysqli_select_db($connection, DB_NAME); And you will get connection to WordPress database...
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "php, database, mysql, wp config, table" }
Questions on WordPress Codex Concept When I was reading the WordPress Codex about outputting the Post and Pages I saw these two Titles at Here > Output a list of all **registered** post types and > Output a list of all **public** custom post types now can you please let me know 1 - What are Registered posts? Is there any un-registered one? 2 - What are the Public Custom Post Types? is there any Private one? Thanks
Adding here. `register_post_type` function have a parameter `public` which controls how the type is visible to authors and readers. If public parameter of a post type is **true** then post type will be `exclude_from_search`, `publicly_queryable`, `show_in_nav_menus`, and `show_ui`. Read more about it in register_post_type function. Also all post types must be registered to use in WordPress. So there is not such thing as `un-registered post type` but a registered post type can have option to be public or not based on what value you supply.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, codex" }
what Format is really need for Video Players? in all new video player plugins for word press there are some various field for various formats !! like : FLV , Mp4 , OGV , Webm , Mp4 for mobile as my Web host have limit of Size i really confused and not know which of these formats is important for play in most browser for example for a video clip with size 40MB in Flv , i will have 180 MB in create 3 format ( Mp4 , flv , Ogv ) is there any standard format that support all browser and html5 video player ??
There is no one format that works on all browsers, for example, Firefox won't play MP4 files due to FF not having the license to use the MP4 codec. You definitely need OGV and MP4 versions, the others will depend on other browsers and choice, it's better to upload all versions to give you piece of mind the video will work for everyone.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "html5" }
Post to type posts in subdirectory. I would like to do the following: I have a blog with my domain **_www.examplesite.com_** and got some posts on it. But I would like to move some of the posts into a subdirectory **_www.examplesite.com/extras_**. I know it's possible to create a post type for this, but the problem is I don't know exactly how to transform the subdomain into **_www.extras.examplesite.com_** in **_www.examplesite.com/extras_** and move only extra posts categorized into this subdirectory using only codes within functions.php. Is there any way to do this?
The answer to your question is dependent upon your hosting environment (IIS, nginx, Apache, etc.). In a nutshell, you are looking to perform a redirect while preserving the original query. Consider < for an example of one such redirect being performed within nginx.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, add submenu page" }
How to import and export settings from live customizer? How many WordPress developer are working with live customizer for controlling theme settings? Do you people allow users to import and export theme settings? Any examples or tutorials would be very helpful.
I recently built this for one of my themes... Export: < Import: < That file actually contains an entire admin page with the export data and import textarea so you could simply get that and modify it to suit your own needs. I hope that helps!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme customizer" }
run shortcode in excerpt of single custom post type Hi because of the way my theme is set up, I need to run a shortcode inside the excerpt of a custom post type (services). This is the code I have so far... function do_my_shortcode_in_excerpt($excerpt) { if ( 'services' == get_post_type() ) { return do_shortcode(wp_trim_words(get_the_content(), 55)); } } add_filter('get_the_excerpt', 'do_my_shortcode_in_excerpt'); This works fine (I'll need to increase the 55) but it stops the excerpts appearing everywhere else. I only want this filter to run on excerpts associated with services - leaving other excerpts unaffected. Can anyone assist me?
You just forgot to `return` the excerpt for the other post types. Try for example: function do_my_shortcode_in_excerpt( $excerpt ) { if ( 'services' == get_post_type() ) $excerpt = do_shortcode( wp_trim_words( get_the_content(), 55 ) ); return $excerpt; } add_filter( 'get_the_excerpt', 'do_my_shortcode_in_excerpt' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "filters, shortcode, excerpt" }
Where should I put this custom data? My client needs to store food nutrient data in his site's database. I have food name, calories, protein, fat, carb, fiber and other data to store for many food items. I'm a developer but new to WP. Where is the best place to store this information? A custom table, custom post, regular... Thanks!
Supposing that each food item is treated as a post (perhaps even a custom post type), and the parameters (name/calories/etc.) are attributes of this post, you would do well to treat them as post meta fields. Various means exist to grant end-users the ability to maintain custom fields; my preferred option is Developer's Custom Fields, but other solutions exist. Regardless of the method used, the assumption is that for a given post certain meta fields have been populated and must be queried at runtime. Within a loop (in particular, after invoking `the_post()`), and for a particular custom field (for illustration I will use "calories"), you would retrieve the value using `get_post_meta()` as shown below: echo "Calories: " . get_post_meta(get_the_ID(), "calories", true); Some assumptions are made here (that you're in a page/post loop, the data you are requesting has already been entered, and the name of your custom field is "calories").
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, database" }
Custom Fields Question I'm new to wordpress and I am trying to understand these custom fields. I read the wordpress codex page refering to custom fields but I have some questions. I take for example my site. I created a custom field named "country_flag". I want this custom field to store for every post a link to a icon displaying a country flag. This icon i want to place on my site after the post title to show guest in which language the post is. On the codex page it tells me to place `<?php the_meta(); ?>` in my template. But if i have more custom fields and I want only one to be shown in my template where i put the `<?php the_meta(); ?>`, what code should I place?
If you want to display a single custom field (post meta) then you can use: get_post_meta(); It has three arguments. 1. The ID of the post 2. The name of the post meta field (country_flag) 3. Whether or not the value returned is a single string (in your case it will be); So the usage might be something like this: $country_flag = get_post_meta( $post->ID, 'country', true );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, customization, links, template tags, icon" }
Remove whitespace before the_excerpt(); I need to delete the whitespace that `the_excerpt();` function returns me. I noticed it gives me whitespace before the whole text only where in the page images goes first and only after goes text. I tried `str_replace();` and `trim();` none of them helped. !The image of how it looks
This is caused by the line break between the first image in the post and the body content of the post. Just delete the one line of space between the two and it will working fine.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "excerpt, formatting" }
Escape HTML on WP input I am slightly stuck on creating a widget, it has an input (bit like the default text widget) but got an issue adding html into it. My code is: $instance['content'] = ( ! empty( $new_instance['content'] ) ) ? esc_html( $new_instance['content'] ) : ''; This works partially as it let me saves the HTML (an iframe) but displays it as code in the frontend, I need it to convert the iframe code to a working video. I have also tried: $instance['content'] = ( ! empty( $new_instance['content'] ) ) ? strip_tags( $new_instance['content'] ) : ''; but it won't let me save the iframe content (it clears the box). Which function do I need to use so my widget behaves the same as the default text widget.
The default text widget - `WP_Widget_Text` \- can be found in `wp-includes/default-widgets.php`. The input is handled like this: * `stripslashes( wp_filter_post_kses( addslashes( $text ) ) );` for the text; I assume this should work likewise for your custom widget. Additionally there is: * `wpautop( $text )` on the output, if the filter is set to do that; But optimally you're taking a look at the source yourself. Additionally the codex articles: * Validating Sanitizing and Escaping User Data; and * Data Validation give you an good overview about sanitizing, escaping and validating possibilities with WP.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "widgets" }
How to get better performance for redirect from domain.tld/35 to domain.tld/full-permalink? Based on this answer I created a function to change the shortlink from domain.tld?p=435 to domain.tld/435 and redirect domain.tld/435 to domain.tld/full-permalink: function shorter_shortlink() { global $post; $shortURL = get_bloginfo('url').'/'.$post->ID; if(!empty($shortURL)) { return $shortURL; } else { return get_bloginfo('url').'/?p='.$post->ID; } } add_filter('pre_get_shortlink', 'shorter_shortlink'); add_action( 'wp', function(){ global $wp; if( is_numeric( $wp->request ) && empty( $wp->query_vars['page'] ) ) { wp_redirect( get_permalink( absint( $wp->request ) ), 301 ); exit(); } }); While testing it seems that this approach is not the best for the performance. I wonder if there´s a better solution for this matter?
I fear the answer here is that redirecting will just never come with good performance. Especially doing it via PHP, because then it's handled rather late. You could think about doing it via apache in particular the `.htaccess` file, which intercepts way earlier, before PHP/WordPress even come into play. Which will be better, but of course it still will be a redirect. But as @birgire pointed out in his comment, you need the concrete/exact rules, so this isn't very practical. Another idea, doing some javascript "magic", same comment. If you ask me it's not worth it, either you redirect or you don't, just decide.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "redirect, performance" }
How To Get Some Data From WordPress Database Using WordPress $wpdb Query? I am trying to get some data from WordPress database tables in a plugin. For that, I am using the below code... global $wpdb; $findID = $wpdb->get_var("SELECT ID FROM wp_posts WHERE post_name = 'hello-world'"); echo $findID; But it not giving me the post ID in `echo`? Is there anything wrong...???
Just to clarify the `get_var()` method of `$wpdb` does work just fine in this context: global $wpdb; $helloworld_id = $wpdb->get_var("SELECT ID FROM wp_posts WHERE post_name = 'hello-world'"); echo $helloworld_id; Actually it is more practical in this context, because a single variable is returned, which is what is actually wanted.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 1, "tags": "wp query, database, query, wpdb, sql" }
Generating List of Tags from Custom Post Type I have created a Custom Post Type "model" with corresponding tags "model_tag". I am trying to generate a list of tags chosen for the post. I am able to generate a string using the code below, however I would like to output it as a list. <?php $terms = get_the_terms( $post->ID, 'model_tag' ); if ( $terms && ! is_wp_error( $terms ) ) : $limits_links = array(); foreach ( $terms as $term ) { $limit_links[] = $term->name; } $model_tag = join( ", ", $limit_links ); ?> <?php echo $model_tag; ?> <?php endif; ?>
If all you're looking to do is list out the model tags as list items, this should work for you: $terms = get_the_terms( $post->ID, 'model_tag' ); if ( $terms && ! is_wp_error( $terms ) ) : $model_tags = '<ul>'; foreach ( $terms as $term ) { $model_tags .= '<li>' . $term->name . '</li>'; } $model_tags .= '</ul>'; echo $model_tags; ?> endif;
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom taxonomy, tags" }
$wpdb->get_var multiple queries in one database check I am using the $wpdb->get_var php code to get the first name and last name on the records, in the wp_usermeta table... But because the field value is stored in the same cell, I don't know how to merge it into one string. Right now I do it like this: $_EmployeeFName = $wpdb->get_var( $wpdb->prepare("SELECT `meta_value` FROM `wp_usermeta` WHERE `meta_key` = 'first_name' and `user_id` = %d ", $_REQUEST['empid'])); $_EmployeeLName = $wpdb->get_var( $wpdb->prepare("SELECT `meta_value` FROM `wp_usermeta` WHERE `meta_key` = 'last_name' and `user_id` = %d ", $_REQUEST['empid'])); Is there a way to do that in ONE pull from the database? I don't want to do this a lot, to save the database from so many pulls... I don't know how to do it though. do you? Thanks, Richard
Why do your own database queries? Use the WP functions to do it for you. $empid = (int) $_REQUEST['empid']; $name = get_user_meta($empid, 'first_name', true) . ' ' . get_user_meta($empid, 'last_name', true);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "mysql, wpdb" }
How to recover password from a user I have an old blog in wordpress. I can't remember my old password. The last time I acessed, I put the site in maintenance with a plugin. I have accesse to database and FTP, but I don't know how to recover the password or create a new one. Website: www.felipestoker.com/encamisetados
You cannot recover a password, you can only reset it to something new. We have an article with several ways to do that in the documentation. Pick one of those methods. <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "password" }
Add class to comment form div when comment-reply button is clicked I'm using the comment-reply script to move the comment form under thread when replying to a specific comment. Comment form is being displayed in theme with: <?php comment_form(); ?> The comment form output: <div id="respond" class="comment-respond"> I'd like to add a class to the div ONLY when it's a reply and not a new comment. So, on reply click it would change to: <div id="respond" class="comment-respond reply-to-comment"> Right now when the reply button is clicked and the form moves under the comment I'm not seeing any code changing at all.
You'd probably have to do this in javascript, but I'm guessing the reason you want to add a class is to style it differently? If so, just use different styles for #respond that is inside a reply container. So perhaps the style would be `.comment-replies > #respond` or something similar.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "comments, comment form, scripts" }
How to hide a Sidebar from other admins? Is there a function way that I can hide a sidebar from other admins? Meaning they can't see it so they can't edit its content but it is still there? I'm wanting to place my copyright, developed by footer in a sidebar via a widget so it will allow me to create more footers like this for various layouts, but I don't want the client to have access to this sidebar. I know I can do it through a conditional css function, but is there a function I can do to achieve this without just using css? Something Wordpress native? Similar Example: function Hide_Admin_Bar() { if (!current_user_can('My_User_Name_Here') && !is_admin()) { show_admin_bar(false); } }
Here is the solution I've used which is css based. global $pagenow; if (in_array($pagenow, array('widgets.php'))) { function Only_show_to_webmaster_user_things_by_css() { global $current_user; $username = $current_user->user_login; if ($username == 'Your_Username_Here') { } else { ?> <style>#Sidebar_ID_Here{display:none !important;}</style> <?php } } add_action('admin_head','Only_show_to_webmaster_things_by_css'); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "sidebar" }
Migrating my existing WP site to localhost I already have an existing WP site running, and am currently learning how to work on my site locally. I followed the tutorial at < and have WP installed locally now, works fine. However this is the 'vanilla' WP installation; what I need is to migrate my entire site locally so I can work on the existing site locally. What would be the best way to go about it?
I use the plugin Duplicator. This will copy all files and databases in one package, migrate the databases,... You can even set up filters to exclude/include certain files. It takes 4-5 minutes to migrate everything to localhost and vice-versa.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "migration" }
the_post_thumbnail() doesn't always return selected size In my theme's archive template, I'm using the_post_thumbnail('list-thumb-small'); to get a specific thumbnail size for each post. But that doen's work on all posts. Some posts display their featured image in full size, while others display the correct "list-thumb-small" size. I have set the custom image size in functions.php: add_image_size( 'list-thumb-small', 225, 185, true ); Why is this happening and how can I fix it?
Those might be old images. Image uploaded to WordPress before adding this new image size code will not resize automatically. You will have to resize old images again. There is a great plugin for that. Use Regenerate Thumbnails plugin to auto generate thumbs for all images. If you ever add a new image size then always resize images again with this plugin.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post thumbnails" }
Multiple do_shortcode in page template Is it possible to nest multiple shortcodes with `do_shortcode`? Using visual composer and easytable with the visual editor, the classic editor displays: [vc_row][vc_column width="1/1"][vc_accordion][vc_accordion_tab title="Section 1"][easytable]table stuff[/easytable][/vc_accordion_tab][vc_accordion_tab title="Section 2"][/vc_accordion_tab][/vc_accordion][/vc_column][/vc_row] I have attempted something like this: echo do_shortcode( '[vc_row][vc_column width="1/1"][vc_accordion][vc_accordion_tab title="Section 1"][vc_column_text] [table] ' .$sometabledata. ' is some data [/table][/vc_column_text][/vc_accordion_tab][vc_accordion_tab title="Section 2"][/vc_accordion_tab][/vc_accordion][/vc_column][/vc_row]' ); However, this seems to generate the accordion, but the table is then lost. Separately the table works with: echo do_shortcode( '[table]mydata[/table]' );
Okay, you need this: <?php echo do_shortcode('[your-first-shortcode]'.'[your-second-shortcode]'); ?> Just write a dot between your shortcodes... Try: <?php echo do_shortcode( '[vc_row][vc_column width="1/1"][vc_accordion][vc_accordion_tab title="Section 1"][vc_column_text]'.'[table]'.$sometabledata.'[/table]'.'[/vc_column_text][/vc_accordion_tab][vc_accordion_tab title="Section 2"][/vc_accordion_tab][/vc_accordion][/vc_column][/vc_row]' ); ?>
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, shortcode" }
Blog pages show at most unrecognized by code This is the code I use to grab my post archives and style the first post differently. (Full code linked.) This code does not seem to be recognizing the "Blog pages show at most" setting under Settings > Reading. I am unsure why. Help is appreciated! <?php while (have_posts()) : the_post(); ?> <?php $postvariable++; /* count the posts */ ?> <!-- Begin: Post formats --> <?php if ( has_post_thumbnail() ) { ?><?php } ?> <?php if ($postvariable == 1) echo '<div class="excerpt first-post">'; else echo '<div class="excerpt">'; ; ?> <
You must set your post counter outside your loop first before it will work. If you turn debugging on, you will get an undefined variable notice. You can do something like this just outside your loop before the loop starts $postvariable = 1; Alternatively you can make use of the build-in post counter, `$wp_query->current_post`. It starts counting at 0, so to target the firts post, you can do if( 0 == $wp_query->current_post ) { //do something for first post }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "archives" }
Function to get the name in database table from the comma separated string I already created admin column in WP using this code: add_filter('manage_pages_columns', 'page_custom_cols', 10); function page_custom_cols($pages_columns, $post_type) { $pages_columns['user_group'] = 'User Group'; return $pages_columns; } Now I added the function to get the user group id, this field is already in wp_post table but in a comma separated text just like this: " 1,7,2 " and I was able to display it using this function: add_action('manage_pages_custom_column', 'display_page_custom_cols', 10, 2); function display_page_custom_cols($col_name, $post_id) { if ('user_group' == $col_name) { $pages = get_post($post_id); echo $pages->group_access; } } And it was showing now: < My problem right now is I want to display the the User Group Name not the ID It was in the table 'custom_user_group': < Please help.
Not tested but this should work: add_action('manage_pages_custom_column', 'display_page_custom_cols', 10, 2); function display_page_custom_cols($col_name, $post_id) { global $wpdb; $user_group = $wpdb->get_results("SELECT * From custom_user_group",OBJECT_K); if ('user_group' == $col_name) { $pages = explode(',',get_post($post_id)); $output = array(); foreach ($pages as $page ) { $output[] = $user_group[$page]->GroupName; } echo implode(',',$output); } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, loop, database, csv, get post" }
Wordpress live site images not displaying I transferred a website from localhost to a live domain. The images are not showing up and all pages link to localhost. How can I change this? Please guide. Thanks.
You can either use the SQL query or use the Velvet Blues WordPress plugin. Via SQL UPDATE wp_posts SET post_content = REPLACE(post_content, 'localhost/test/', 'www.yourlivesite.com/'); This will resolve the broken links and missing images issue.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "domain" }
External PHP file & Pretty Permalink I'm working in developing REST API for a WP based website. Endpoint is ` I've included `wp-load.php` in the top of the file to access WP functions etc. However, ` is loading normally in browser (not output as no parameter is passing). When I'm passing any parameters like ` I'm WordPress getting non found error page. Most wired part is, when I've disabling Pretty Permalink, everything is working normal.
I can't say I've ever tried including `wp-load.php` directly, but I've had success using: define("WP_USE_THEMES", false); include("wp-blog-header.php"); ... when trying to invoke Wordpress stack in a non-templated workflow. `wp_blog_header.php` does make the call out to `wp-load.php` but also wires up some other stuff (such as calling `wp()`).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permalinks, wp load.php" }
Images not showing after moving site I've tried all the options suggested in other similar questions, and I'm stuck. My images are not showing after moving a site from my local machine to another server. I've searched the database, and there is no trace of the old domain, so using a search and replace won't help. I've checked the wpconfig and there is no trace of the old domain. Can anyone suggest a solution? If I check the media library, the files are all there and they have the correct URLs (the new server), but the links to them in the site are to the old local server.
Doing a search via PHPMyAdmin did not show up any instances of the wrong URL. However, when I searched and replaced using this plugin < I found certain URLs were incorrect. Some changes could not be made with the plugin as they were serialized.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, database, links" }
Which delete query is better with prepare or delete Just wondering which of the two delete queries would be the preffered method $qdel = $wpdb->query($wpdb->prepare("DELETE FROM $shopping_meta_table WHERE meta_shopping_key = '%s' AND wp_user_id = %d", 'product-2', $id)); or $qdel = $wpdb->delete($shopping_meta_table,array('meta_shopping_key' => 'product-2', 'wp_user_id'=>$id));
By your **reputation** , It seems that you know about the wordpress very well. Use of `prepare` method in query is to make sure we're not dealing with an illegal operation or any illegal characters.So I recommend you to delete with the `prepare` method. Other than that, you might be aware of **SQL INJECTION**. Before release of **wordpress 2.5** , there was `$wpdb->escape()` to prevent SQL Injection whose work was to prevent SQL injection attacks and keeping the bad dudes out. Since WordPress 2.5 a new $wpdb function has been included called ‘prepare’, whose work is to prevent SQL escapes. So All data in SQL queries must be SQL-escaped before the SQL query is executed to prevent against SQL injection attacks. The `prepare` method performs this functionality for WordPress, which supports both a sprintf()-like and vsprintf()-like syntax. Read more about **SQL escaping**. Prepare Function.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization" }
Remove Archives in category title How I can remove word " _Archives_ " in head title in category page? I'm using the Twenty Twelve theme and WordPress 4. <head> <title>"name of category" Archives | "name of sites"</title> </head>
If you are using yoast SEO plugin then the easiest method is to remove the archive word from "`titles & metas-> Taxonomies->category`" find: %%term_title%% Archives %%page%% %%sep%% %%sitename%% replace it with: %%term_title%% %%page%% %%sep%% %%sitename%%
stackexchange-wordpress
{ "answer_score": 6, "question_score": 5, "tags": "theme twenty twelve, categories" }
theme continuous deployment from bitbucket to windows azure I need to set up continuous deployment of a wordpress theme controlled via bitbucket to a Windows Azure hosted wordpress install. One of the sites I run has had a external agency develop a theme that they will be supporting the development of for the foreseeable future. Is there a set method I should use? Azure wants to set up source control for the root of the site, but this would include the whole wordpress install, which seems a bit crazy. How do I got about this? Thanks
It turns out all that is required is a .deployment file in the repository [config] DEPLOYMENT_TARGET = D:\home\site\wwwroot\path\to\theme
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, git" }
How to share posts in Wordpress Multisite? It's the first time I am using the multisite option. I must be searching for the wrong terms, because I can't find the answer to what I think it's a simple problem... I have 3 sites. 1. Group Landing site 2. Group 1 site 3. Group 2 site Essentially, Group 1 and Group 2 will have separate contents. However the Group Landing site will have content from both. I would rather not have the user enter the content twice. Using Multisite, is there a way for me to poll content from Group 1 and Group 2, and display it in Group Landing? If not, what's a better option to share content between sites?
You could use the function `switch_to_blog` Example: switch_to_blog( $site_id ); $post = get_post( $post_id ); restore_current_blog(); It should do exactly what you need. After switching you can use a custom query to get the relevant information
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "multisite" }
Get access to Wordpress when logged out I have a WP site with bbPress installed and bbPress Like Button (a like button plugin). I was trying to import a phpBB forum to bbPress. I'm having problems doing this and in the process must have decactivted bbPress. Now when I try to log in at wp-admin or view the site I get a page saying. 'bbPress Like Button needs bbPress installed and activated in order to work.' This is on QA server and so I can't get access to the files. Is there any way to fix this - Is there any way to access the dashboard to re-activate the plugin
So the plugin mishaps are blocking you from signing into the dash? You will likely need server access or someone who has this access if you're not using version control. You can just rename the folder for the plugin that you want to de-activate (BBPress Like Button). That will force it to de-activate since the WordPress will lose track of it. Then log into the dashboard, activate the appropriate plugin (BBPress) and then return the plugin folder (BBPress Like Button) back to what it was before you changed it. Then you can activate BBPress Like Button once you're sure it has what it needs and won't break your admin access. This question might also be helpful for you, see Rarst's answer: How To Activate Plugins via Code?
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, wp admin" }
How to edit label_submit styling? This is going to sound like an easy fix, but I am looking to style my submit comment button on my comment form. Currently the code in the $args = array looks like this: `'label_submit' => __( 'Post Comment' ),` I am wondering how to apply styling to this button.
You can target your submit button in css like this. This will look for a input element with `type="sunmit"` in container id `respond`. So make sure your container id is `respond` otherwise change it too. #respond input[type=submit] { /* your styles */ }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, functions, comments template" }
404 on child page when parent page slug is identical to custom post type The internet is swamped with this issue but all the results were from 2010-2011 so I wanted to check if there was any advancement in the matter. I have the following scenario: * Created a custom post type "videos" * Created a parent page "Videos" * Created a child page "New Video" * Changed permalinks to `%category%/%postname%` WP automatically created the permalink for the child page as `www.example.com/videos/new-video` but the page leads to a `404 Not Found` error. * Re-saving permalink settings does not solve the problem * Changing the parent page slug to "videoss" **solves** the problem * Changing the custom post type to "video" **solves** the problem Is there any way to have both custom post type and parent page slug set to "videos" under the aforementioned permalink structure?
I ended up changing the post type to 'video' to avoid the slug conflict with page 'Videos'. I it a WP default behavior to give priority to the post type over the page slug: How to make pages slug have priority over any other taxonomies like custom-post, post or category
stackexchange-wordpress
{ "answer_score": 4, "question_score": 5, "tags": "custom post types, permalinks, 404 error, child pages" }
WordPress site does not display content I migrated a live site to my system and ran it via xampp. I am unable to see the contents of the page ( I can see the page loads fine but no text is displayed and site keeps connecting to the live site). Please advice me what needs to be done. Thanks.
An over simplified version of doing this is to download WordPress Serialized Search and Replace tool And drop it onto your server go to the location of where you have uploaded it. Then simply search for your old url, and replace with the new. This will do this for every post type, post data and if your theme has settings it will also replace in the settings. Regards TTech Second thing you could do is this method and start your move from scratch < Download and install this plugin on server 1, active the plugin select it from the menu, run through the steps. You will get 2 files, an installer and a file zip. upload both to server 2. go to < and run through the steps Bingo site has moved.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "xampp" }
I think emoji are killing my WordPress site… How can I debug? I have had a rather frustrating last couple of days… after quite a bit of trial and error, I have come to the suspicion that emoji are killing my WordPress installation. Specifically, emoji in the settings of my theme. !Screenshot In retrospect, I can see that even trying to use emoji was a bit of a risky proposition. As I understand it, they are not officially a part of the UTF-8 character set. For the time being, I have tried to carefully go back through all of my theme settings and eliminate any use of emoji anywhere. But now, I would like to find out exactly how they are breaking WordPress and where. Trouble is, I'm not familiar with PHP beyond the basics I've needed to pick up for theme customization. Where should I begin to debug this problem?
This is a limitation of MySQL’s UTF-8 implementation: it supports just a limited set of valid UTF-8 characters. You can convert your database to `utf8mb4`, and emojis will work. But there may be other side effects. See ticket #21212 for details.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "php, theme development" }
Different background images on different sites I use wordpress 4.0.5 and Minamaze Theme (< The Minamaze Theme gives me the opportunity to add custom CSS, without having to edit any files, so I added: body, #body-core { background: url( fixed; background-size:100% auto; } Adding this CSS sets the background properly. What I want to achieve now is, having differnt (like 2 or 3) background images on different pages. Has anybody an idea how I could do this? Thanks in advance
Take a look in the source code, and you'll see the body tag on every page and/or post has a unique class associated with it (postid-1241 for example). Select that class and change the background image there. Example: body.postid-1241 { background: url( fixed; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "images, custom background" }
How do I delete thousands of unattached images? I have thousands of unattached images with no files. How do I delete them all quickly? > ls: cannot access wp-content/uploads/2014/09/jeep cherokee patriot-Ekza.jpg: No such file or directory
That's a lot of unattached images. If you have couple of hundred images then you can delete them manually from media library. 1. Click 'Screen Options' at the top right and set 'Show on screen' to 200. 2. Click 'Apply'. 3. Click the checkbox just under 'Bulk Actions' to check all images on the page. 4. Select 'Delete Permanently' in the 'Bulk Actions' dropdown. 5. Click 'Apply'. But if you have thousand of unattached images then it would be best to use a plugin. DNUI (Delete not used image) plugin will do that for you. It will let you delete tons of images from media library. Or use DX Delete Attached Media
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "images, attachments, customization" }
How can I reduce file upload size? The current file upload size limit is 128MB. I want to reduce this to 1MB. I do not have access to php.ini file. I do have access to .htaccess and I could use this solution. But why isn't there a method for doing this in the `functions.php` file? ** UPDATE ** So this, over at Stackoverflow, basically says why: > Those settings are not going to have any effect when set via ini_set > > The reason is that PHP needs those values before your script is even executed. When an upload occurs, the target script is executed when the upload is complete, so PHP needs to know the maximum sizes beforehand. > > Set them in php.ini, your virtual host config, or in a .htaccess file. A typical .htaccess file would look like this > > `php_value post_max_size 30M` > `php_value upload_max_filesize 30M` So the question remains; Is there a way to set max upload size in WP `functions.php`?
Absolutely, you can simply hook into `upload_size_limit` and set a maximum filesize: // Change the upload size to 1MB add_filter( 'upload_size_limit', 'wpse_163236_change_upload_size' ); function wpse_163236_change_upload_size() { return 1000 * 1024; }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "uploads" }
Change user role when post approve I have two roles. A: The user sends a post for moderation B: The user publishes posts without moderation For new users the role of A. How do I do if I approve of his first post, the role is changed to B?
You can attach code to change role when post status is changing from "pending" to "published" see documentation: < Then, if user has role "contributor" you can change this to "author": add_action( 'pending_to_publish'. 'my_function', 10, 1 ); function my_function( $post ) { $wp_user_object = new WP_User( $post->post_author ); if ( in_array('contributor', $wp_user_object->roles ) ) { $wp_user_object->remove_role( 'contributor' ); $wp_user_object->add_role( 'author' ); } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "posts, user roles" }
Get Content From Blog Page I have a page that is assigned as the "Blog". What I'd like to allow is the user to add content to this page then display it before the posts show up on `index.php`. I thought I used to be able to do it using this method: <?php $blog = get_option('page_for_posts'); echo apply_filters('the_content', get_the_content($blog)); ?> For some reason it is deciding to pull the first post instead of actually pulling the page content. Is this a bug or is there another method to pull the blog page content?
You are using `get_the_content()` wrong, it can't take a ID, which is what `get_option('page_for_posts')` does return, and generally gets the content of the current post inside the loop, in which it has to be used. To get the actual content of that page you can do: $page_for_posts_id = get_option( 'page_for_posts' ); $page_for_posts_obj = get_post( $page_for_posts_id ); echo apply_filters( 'the_content', $page_for_posts_obj->post_content ); Or: $page_for_posts_id = get_option('page_for_posts'); echo get_post_field( 'post_content', $page_for_posts_id );
stackexchange-wordpress
{ "answer_score": 11, "question_score": 3, "tags": "content, options, blog" }
Template_redirect for child custom post types I currently have a custom post type called 'Services' which has two levels (parent and child). I need to load three different templates within this post type (1 for the parent, and two different ones for the children'. Can anyone please explain how I might go about achieving this? Any suggestions would be greatly appreciated.
All sorted. For any one interested, I simply added in a function (into functions.php) that redirected to my new template dependent on the name of the post (you could also use the ID). add_filter('template_include', 'new_template'); function new_template($template){ global $post; if($post->post_name == 'mortgage'){ $template = get_template_directory() . '/mortgage-template.php'; } return $template; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "templates, template redirect" }
Relative time - how to calculate difference beween post publish date and current time I want to calculate the difference between post's publishing time and current time, and I want to read that value as a number (number of hours, minutes, seconds whatever, i just want it to be a number). The reason is I want to do something depending on the post's age. Would this code work? $date = get_post_time('G', true, $post); $current_time = current_time( 'mysql', $gmt = 0 ); $newer_date = strtotime( $current_time ); $postsage = $newer_date - $date; if($postsage < 7200){ ... } // if post is between one and two hours old else if (($postsage >= 7200) && ($postsage <=14400)){ ... } else { ... } Is this code bit valid?
To print relative time on posts automatically we can use `get_the_date` filter. We will check the time difference and print it in human readable form. // Relative date & time function wp_relative_date() { return human_time_diff( get_the_time('U'), current_time( 'timestamp' ) ) . ' ago'; } add_filter( 'get_the_date', 'wp_relative_date' ); // for posts add_filter( 'get_comment_date', 'wp_relative_date' ); // for comments And in your theme use `<?php echo get_the_date(); ?>` to print relative time. If you do not need relative time for comments then remove following from code. add_filter( 'get_comment_date', 'wp_relative_date' ); // for comments **EDIT** To get time difference in seconds. Use this. $seconds = current_time( 'timestamp' ) - get_the_time('U'); Now you can use `$seconds` in your if conditions.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "date time, timestamp" }
How do I add custom fields to posts without having to manually add everytime I post? I am new to wordpress but I was trying to add custom fields to certain posts but I don't want to manually add every time. I saw there is a custom post type class that you can specify but I didn't find any related info when I searched. Essentially I want to add metadata so that I can add search functionality on posts. ie. rating, difficulty, etc.
The Custom Field Template plugin will let you define default custom fields for the write post/page screen. Might be a simple solution. I'm not affiliated with this plugin, just a user.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom field" }