INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
WordPress API - Get Drafts I want to check if a post already exists. This includes to check if the post exists as draft as well. But I struggle a little bit with the wordpress API v2. < Under **List Posts** -> status they say > Limit result set to posts assigned a specific status. > Default: publish I tried to assign the value as parameter, but I get an error response: > {"code":"rest_invalid_param","message":"Invalid parameter: status","data":{"status":400,"params":{"status":"Status is forbidden"}}} I als asign the title of the post to check: > filter[s] = post Title So how to get the posts with draft state? I'm currently using the Basic Auth for developing? I also tried > filter[post_status]=draft but with no success. I have the following plugins installed: WP REST API WP REST API - filter fields JSON Basic Authentication
I think the query parameter that you want for post status is: status=draft Let me know if this doesn't work.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 7, "tags": "api, rest api, draft" }
Child Themes and Updating Parent Theme I have not got a child theme set up for the theme I'm using, though there is an update for the theme now. I've had a google and they say that if you don't have a child theme you will loose your "customisation". When they say customisation are they referring to any code you've altered? As I haven't altered any. Or are they referring to any content, posts, pictures, changes to the home page you've made (through the customise UI in the appearance section). If it does refer to the content, posts etc. is there any easy plugin or other way of easily restoring that to the updated theme, without having to go through setting up a child theme?
They are referring to the source PHP, JavaScript, and CSS and really any other files contained within the parent theme's directory. If you have not modified the files within the parent theme, you shouldn't have much to worry about. Your posts, pages, and other content should not be deleted from updating a theme. It is possible that the updated theme will handle features in different or unexpected ways. You should still back up your site's database and files prior to doing an update as a precaution.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, child theme, updates" }
Method to make definitively static an abandoned WP blog I have a blog, created with WordPress 3.4, which I abandoned some years ago but it is still receiving a good number of visits each day through Google search results. It means a load for my mySQL server and wondered if there was a method to make the blog definitively static. I don't plan to insert new posts, and I don't allow comments on the old ones. Any tip is welcome. Thank you very much.
Install a page caching plugin and configure it for a very very long time. This have the advantage of you being able to post things when you decide that its time to do that again. Side note: abandoned blog creates actual noticeable load on a DB server? I find it hard to believe. front end wordpress, especially in typical blog setting should not have heavy queries. (this is said as a proud owner of two relatively abandoned blogs)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "cache, static website" }
Inserting Post Using wp_insert_post. How to Fill Yoast Plugin SEO Fields I am inserting posts into a database using `wp_insert_post` function once the post is inserted using below line of PHP `$postId = wp_insert_post($array)` I can insert values in my advanced custom fields using `add_post_meta` function but I didn't find anything to insert the SEO title or the meta description specifically in the Yoast SEO plugin. Can anyone help me with this?
You can use the update_post_meta function to insert the Yoast Plugin data. Yoast uses 3 post meta keys for each post: 1. _yoast_wpseo_title ( use for SEO title ) 2. _yoast_wpseo_focuskw (For meta keywords ) 3. _yoast_wpseo_metadesc (For meta descriptio ) You can find all these meta key under postmeta table $new_id = wp_update_post($array); update_post_meta( $new_id, '_yoast_wpseo_title', 'SEO Title' ); update_post_meta( $new_id, '_yoast_wpseo_focuskw', 'keyword1 keyword2' ); update_post_meta( $new_id, '_yoast_wpseo_metadesc', 'SEO Meta Descr' ); Hopefully, It will work for you! Thanks
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "query posts, seo, debug, plugin wp seo yoast, wp debug" }
How to automatically add edit link on frontpage post of any wordpress theme? Hi I searched google for a plugin to do so, I can't find any. Can you recommend me one if not can I create it myself though I'm beginner in wordpress dev ? If yes can you give me some clues. Thanks. Update: I'm not interested in having edit link in admin bar; I bought a plugin which instructs me something I don't want to do by hand on dozens of themes : ![enter image description here]( Please give me an answer, I'm desperate :)
As lot of themes use `the_content()` to display the post content. you can use `the_content` filter hook to add the edit link before/after the content. Since you want this work outside themes, you have to put the following code in a file, and store it in your plugins folder then activate it as a plugin. <?php /** * Plugin Name: Add Edit Link in Frontend * Description: Append post edit link to content * Version: 1.0.0 */ function wpael_content_edit_link( $content ) { $content .= '<br /><div style="font-size: 14px"><a href="'. get_edit_post_link( get_the_ID() ) . '">Edit</a></div>'; return $content; } add_filter( 'the_content', 'wpael_content_edit_link', 10 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, plugin development, plugin recommendation" }
Internationalize Forum Posts Without Translating Them I would like to internationalize my forum. I would like for users to be able to display the forum in 2 languages. The language will be determined by the url. I downloaded a plugin called Polylang to help me with this. This works well until it comes to displaying posts (ie: questions). I'm interested in displaying the posts in their original language regardless of the user's current locale (ie: page elements such as header and footer will reflect the user's locale while the post will be in its original language). I would like a given post to have urls like: www.example.com/blog/fr/some-post www.example.com/blog/ru/some-post Is this possible? The only possibility to do this with Polylang would be to enter the exact same post for each language. But it seems inefficient and incorrect to do this. Does anyone have any suggestions for how I might achieve this? Thanks.
The plugin WPGlobus allowed me to achieve what I stated in the question.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, localization, plugin polylang" }
Add class or ID to any Wordpress function I often find the need to add class or ID's to Wordpress functions. Preferably I would like to do this in the a template (not in `functions.php`). Example: `<?php the_excerpt(); ?>` Will output the excerpt inside `<p>`. How can I add a class to the paragraph so that I get `<p class="something">The excerpt text...</p>`
If you have only one template it's fine to do something like: echo '<p class="whatever">' . get_the_excerpt() . '</p>'; However, if you have multiple templates and want to control the classes centrally, you can make a filter on `get_the_excerpt` as follows (but yeah, that would be in `functions.php`): add_filter ('get_the_excerpt','wpse240352_filter_excerpt'); function wpse240352_filter_excerpt ($post_excerpt) { $post_excerpt = '<p class="whatever">' . $post_excerpt . '</p>'; return $post_excerpt; } You would then simply have `echo get_the_excerpt();` in your template files.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "functions, templates, css" }
wordpress custom post type shows other cpt posts in admin menu I have a wordpress website with 4 custom post type and Suddenly 3 of them show the other one posts in admin menu. what is the problem?
i don't know why but the problem solved after i deleted the following question code from my function.php file // Show posts of 'post', and 'news' post types on archive page add_action( 'pre_get_posts', 'add_my_post_types_to_query' ); function add_my_post_types_to_query( $query ) { if ( is_archive() && $query->is_main_query() ) $query->set( 'post_type', array( 'post', 'news' ) ); return $query; } <
stackexchange-wordpress
{ "answer_score": -1, "question_score": -1, "tags": "custom post types, admin menu" }
Preserve Javascript Through Customizer Preview Navigation In the Customizer you can add some javascript and put your control transport to `refresh` so that whenever the user changes a setting it automatically gets reflected onto the website preview panel: // Body Background Color wp.customize( 'body_bgr_color', function( control ) { control.bind( function( value ) { $( 'body' ).css( 'background-color', hex2rgba( value, 1 ) ); } ); } ); I'm enqueueing my script using the `customize_preview_init` hook. The issue happens whenever the user users the main navigation to go to the next page - the javascript changes are lost but preserved on the Controls Pane. How can I preserve or rerun the javascript whenever the user navigates to a new preview page?
Since I'm saving everything on hard save ( button click ) I was trying to avoid updating all the options via ajax. What the below does is as the preview pane is setting up the JS binding, I trigger a "change" which will reapply the controls value to the element. I'm certainly open to better options but this worked in my case: jQuery( document ).ready( function( $ ) { // Body Background Color wp.customize( 'body_bgr_color', function( control ) { control.bind( function( value ) { $( 'body' ).css( 'background-color', hex2rgba( value ) ); } ); $( control ).trigger( 'change' ); } ); } );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "javascript, theme customizer" }
Is there a predefined callback function for custom categories? I am trying to create a meta box _(with the same feature as the category meta box, the one that searches categories)_ , except I want to make one that searches a custom category. I'm hoping that I can rely on a predefined callback function that will work with custom categories. I tried the method from this article but to no avail: add_meta_box( 'metaboxID', "Meta box Title", 'myCustomPostType_myCustomCategory_meta_box', 'myCustomPostType', 'side', 'high' ); When using `add_meta_box`, is there a predefined callback function for custom categories, such as `post_categories_meta_box`?
The callback you're looking for is `post_categories_meta_box` which we can use via a custom callback. // Add your custom meta box. function your_custom_meta_box() { add_meta_box( 'your-custom-meta-box', 'Custom Meta Box', 'my_taxonomy_meta_box_cb', 'post', 'side', 'high', null ); } add_action( 'add_meta_boxes', 'your_custom_meta_box' ); // Our custom callback. function my_taxonomy_meta_box_cb( $post, $box ) { // Pass in the taxonomy we'd like to use. $box[ 'args' ][ 'taxonomy' ] = 'listing_category'; post_categories_meta_box( $post, $box ); } Thanks to @birgire for pointing out how not to duplicate code. :-)
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "metabox" }
How to list all titles of posts on a specific page? How to list all titles of posts on a specific page? I like to show my titles of posts on a specific page. It is more effective to get know what author have written than scroll all pages or navigate using archive widget. I have made page template for my Twenty Fifteen child theme, but I don't know that code I need to show titles with links to posts.
Paste this into your page template. It will output a list of all posts (without pagination). <?php // the query $all_posts = new WP_Query( array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => -1 ) ); if ( $all_posts->have_posts() ) : ?> <ul> <?php while ( $all_posts->have_posts() ) : $all_posts->the_post(); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endwhile; ?> </ul> <?php else : ?> <p><?php _e( 'Sorry, no posts were found.' ); ?></p> <?php endif; ?> <?php wp_reset_postdata(); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "page template, wp title" }
how to force tag page layout to use same as search layout? I have remarked that when clicking on a tag I have a list of posts displayed differently that when I use search box. How to force tag page layout to use same as search layout for any template ?
You can tell WordPress to use the `search.php` template whenever viewing tags by using the `template_include`. It works like this: function wpse_240429() { // IF we're planning on loading a tag template if( is_tag() ) { // Try to locate the search.php template $search_template = locate_template( 'search.php' ); // If the search template exists if( ! empty( $search_template ) ) { // Use search.php for display purposes return $search_template ; } } } add_action( 'template_include', 'wpse_240429' ); You shouldn't have to mess with things like `pre_get_posts` as the query should already be pulled.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, plugin development, theme development, templates, template hierarchy" }
Missing a text-domain esc_attr_e I have a warning via the Theme Check plugin: > Found a translation function that is missing a text-domain. Function `esc_attr_e`, with the arguments 'no-image-selected' Code: data-placeholder="<?php esc_attr_e( $l10n['no-image-selected'] ); ?> I tried: data-placeholder="<?php esc_attr_e( $l10n['no-image-selected'], 'mytextdomain' ); ?> But I'm still getting this error.
Don't know about the error but the strings that are being translated need to be constant strings, not dynamic values. if `$l10n['no-image-selected']` is already translated then use `esc_attr` and not `esc_attr_e`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions" }
Automate specific steps on WordPress install When I set up a WordPress project, I complete the following steps before I get to work: 1. Unpack WordPress 2. Delete pre-installed themes and copy over _s theme. 3. Set up repo via BitBucket and add to SourceTree. 4. Configure wp-config.php remembering to change the wp_ table prefix 5. Switch on debug mode 6. Set up database using a secure password 7. Install WordPress using a secure username and password. Discourage search engines from indexing the site 8. Activate parent / child theme 9. Ensure permalinks are using "Post name" 10. Change admin nickname via user profile to something more secure 11. Switch off show toolbar via user profile 12. Disable comments via discussions 13. Delete default posts and pages I understand that perhaps steps 3 and 4 will need to be done manually, but is there a way programmatically that I can automate the rest?
I'd suggest creating a Yeoman generator. I've written one for my starter theme which you might find helpful if you write your own: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "installation, automation" }
How can I edit the Woocommerce product widget html class? I would like to add a class to the existing woocommerce product widget. The file `'/includes/widgets/class-wc-widget-products.php'` has the following filter. echo apply_filters( 'woocommerce_before_widget_product_list', '<ul class="product_list_widget">' ); Is there a method that I can edit the html `<ul class="product_list_widget">` in that filter within my theme?
You can use the given filter to change the html. Use this in your themes `functions.php` file function wpse240457_add_class($html) { $html = '<ul class="product_list_widget your-new-class">'; return $html; } add_filter('woocommerce_before_widget_product_list', 'wpse240457_add_class', 1, 15);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "woocommerce offtopic" }
Media files exist in upload folder but not showing up In my wordpress, I tried to upload my images by media uploader but it says "couldn't create directory wp-content/uploads/2016/09". Then I create the folders correctly. And now when I tried to upload my files by media uploader, it says "couldn't move to directory wp-content/uploads/2016/09". Finally I uploaded my images in the folder and then checked the media library and the media library saying "no media founds". Why is it happening?
Just by uploading files into the `wp-content/uploads` won't show up in the _Media Library_ , those media ID's needs to be there in the database to show up in the Media Library. If you already have files in the uploads folder and want to add them into the database, you can use this plugin to add files from server. But this is not the correct solution instead fix the permissions issue for that uploads folder.
stackexchange-wordpress
{ "answer_score": 13, "question_score": 22, "tags": "uploads" }
Retrieve tags data in post body I'd like to retrieve tags data and output it in post body inside a template. <a class="tag-button w-button" href="<!--Tag Link-->" style="background-color: <!--Tag Color--> "> <!--Tag Name--> </a> I use default WP Taxonomy for tags, and I created a custom field "tag-color" for Tags using ACF. Does anyone have an idea of what is the best way to do that?
There are two ways to approach this: modify the existing `the_tags` function or build your own. `the_tags` ultimately relies on `get_the_term_list`, which returns a list of hyperlinked tags. You would have to use regular expressions to add classes and styles to that using a filter. That would be quite cumbersome. So, my preferred approach would be to construct a function yourself. Start with an array of tags and loop through them: $all_tags = wp_get_post_tags (get_the_ID(), array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all')); $output = ""; foreach ($all_tags as $tag) { $tag_style = // get that from ACF $tag_link = get_tag_link($tag->term_id); $tag_name = $tag->name; $output .= '<a class="tag-button w-button" href="' . $tag_link . '" style="' . $tag_style . '">' . $tag_name . '</a>'; } echo $output; Note: I didn't test this code, so some debuggin may be necessarry.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "functions, templates, tags, advanced custom fields" }
Custom logo manage by customizer and theme options I have created a custom theme options page and added some theme setting fields and I also added the custom-logo option in Customizer, all thing are working well, but I want the logo also to be managed by the theme options page. That means when I add a logo from theme options page it also updates on the customizer page and vice versa.
Have a look into `set_theme_mod()`: > Creates or updates a modification setting for the current theme and `get_theme_mod()`: > Retrieves a modification setting for the current theme With this you should be able to get the logo: $custom_logo_id = get_theme_mod( 'custom_logo' ); $logo = wp_get_attachment_image( $custom_logo_id, 'full' ); This would set the attachment 12 as the logo $attachment_id = 12; set_theme_mod( 'custom_logo', $attachment_id ); Hope, this helps :)
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "theme customizer, theme options, logo" }
get_terms sort order with child categories of varying depth I'm using `get_terms()` to search through WP categories. I'm trying to order them all by name. The code below doesn't work, apparently because there are multiple levels of child categories involved. How do I sort everything by name (whether they are parent or child categories)? $searchedterms = get_terms( 'category', array( 'name__like' => $s, 'orderby' => 'name', 'order' => 'ASC', 'hide_empty' => true ) ); Example: Alpha (parent) * Gamma (level 1 child) * Phi (level 2 child) Beta (parent) * Epsilon (level 1 child) * Kappa (level 2 child) Zeta (parent) should be returned as Alpha, Beta, Epsilon, Gamma, Kappa, Phi, Zeta.
Thank you for all the comments! With your help I managed to rule out a standard Wordpress issue. I couldn't find the culprit (As @DaveRomsey suggested, it could be one of the `get_terms` or `get_terms_orderby` hooks altering results). In any case, I solved it by sorting the array: $searchedterms = get_terms( 'category', array( 'name__like' => $s, 'orderby' => 'name', 'order' => 'ASC', 'hide_empty' => true ) ); function cmp($a, $b){ return strcmp($a->name, $b->name); } usort($searchedterms, "cmp");
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, search, sort, terms" }
Does the "promote_users" capability allow someone to create a new admin account? I've created a "Second Administrator" role to avoid the worst case scenario happening on my WordPress site when I have casual web development contractors. However if I give them the 'promote_users' capability, can they promote a random user to an Admin and then circumvent the limitations in place?
Yes, if you assign 'promote_users' to another user, that user could promote non-site admins to site admin. <
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "capabilities, user roles" }
<a> and <img> tag not working when I try to show the thumbnail image with a href tag to refer to the post page it only shows the link next to the picture and the image is not clickable. echo "<head> <style> img { margin-left: 25px; margin-right: 25px; } </style> </head> <body> <a href=".the_permalink()." blank='_blank'> <img src=".the_post_thumbnail('video')." > </a> </body>"; Anybody knows a fix for that?
Found a solution myself: echo "<head> <style> img { margin-left: 25px; margin-right: 25px; } </style> </head> <body> <a href='".get_the_permalink()."' target='_blank'>"; the_post_thumbnail('video'); echo "</a> </body>";
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, html" }
Network activating; if ( !current_user_can( ‘manage_options’ ) ) locks me out… iHi, I use this snippet in a plugin; if ( ! ( current_user_can( 'manage_options' ) ) ) do something } but problem is, when network activating this on a multi-site installation, I get locked out of admin pages. WP says “You don’t have authority to this page” or something (translating from Swedish). I have, by trial and error, limited down the problem to the function "current_user_can" but is_super_admin gives the same result. I get locked out. Please note that this only happens when network activating on a multisite installation. If I activate the plugin per site everything works as expected. See github for an example of how I try to implement it. How come? I’ve tried it out many times and tried to tweak the code, but I can't get it to work. Any better way of checking it user does NOT have authority to manage options (does not have admin capabilities)?
Thanks for your advice. In fact it is a hook that I fire of with this check. It looks like this (an example, the check is done in two places for different user levels and in two different plugins) // Down locks me out of admin area if network activated... if (!(current_user_can('manage_options'))) { add_action( 'admin_menu', 'ngo_remove_eo' ); } and the function is; function ngo_remove_eo() { remove_menu_page( 'edit.php?post_type=event' ); } I changed it to this; add_action( 'wp_loaded', 'eongo_cleanup' ); function eongo_cleanup() { if (!(current_user_can('manage_options'))) { add_action( 'admin_menu', 'ngo_remove_eo' ); } if(!is_super_admin()){ add_action( 'admin_menu', 'ngo_remove_eosubmenu', 99 ); add_action( 'do_meta_boxes', 'remove_eopost_custom_fields' ); } } and now it works :) Thanks a lot Dave.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "plugins, multisite, wp admin" }
Adding Capabilities to a WordPress User Account Is it possible to add an individual capability to a user account in modern versions of WordPress (4.6.1)? Or are roles the only thing that "admin manageable" for user accounts? If it is possible, where in the admin can you do this?
No there isn't anything built into the core WordPress, I would recommend this plugin: < Or you would use PHP to add a capability to a specific role (or user): <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "user roles, capabilities" }
how to query single product in woocommerce? I'm trying to query a single product. And I searched it to google on how to do it and a found this code. do_shortcode('[product_page id="{$product_id}"]'); but this dispaly the whole content of products. All I want is just an image,description and the price. How can I do this using WP_QUERY()?
If you want to use the `Wp_Query` for selecting the single product from the database you have to pass the `p` in the `$args` so that if fetches the data and the `post_type` should be as `product`. > Follow up the Normal `$args` method along with that you have to add the following lines of code. <?php $params = array( 'p' => 'YOUR PRODUCT ID', id of a page, post, or custom type 'post_type' => 'product' ); $wc_query = new WP_Query($params); ?> <?php if ($wc_query->have_posts()) : ?> <?php while ($wc_query->have_posts()) : $wc_query->the_post(); ?> <?php the_title(); ?> <?php the_content(); ?> <?php endwhile; ?> <?php wp_reset_postdata(); ?> <?php else: ?> <p><?php _e( 'No Product' ); ?></p> <?php endif; ?>
stackexchange-wordpress
{ "answer_score": 3, "question_score": -1, "tags": "woocommerce offtopic" }
Using '$' instead of 'jQuery' in WordPress jQuery included with WordPress is in compatibility mode. To avoid conflicts with other libraries we can not use the '$' shortcut for 'jQuery'. To use the '$' sign we use: jQuery(document).ready(function($) { $('#myid').css({'background': 'black', 'color':'white'}); }); This works. But my question is how to do the same with window load. I have been facing this problem since last few projects. So, thought better to make the concept clear. jQuery(window).load(function($) { $('#myid').css({'background': 'black', 'color':'white'}); }); With this I get an error that says : "$ is not a function". So, I am unable to use $ inside of the window.load code block. So, can anyone help how I can use the $ shortcut inside window.load?
Using a self invoking anonymous function that passes the jQuery object will do the trick: (function($){ $(window).load(function(){ $('#myid').css({'background': 'black', 'color':'white'}); }); })(jQuery); //Passing the jQuery object as a first argument
stackexchange-wordpress
{ "answer_score": 8, "question_score": 4, "tags": "jquery, javascript" }
wp_delete_attachment not working with multiple values I'm using an `<input>` tag that stores the values of multiple attachment image ids and it's not working. Can anyone tell me where the problem is? <input type="hidden" name="jfiler-items-exclude-imgid" value="["4602","4603"]"> if (isset($_POST['jfiler-items-exclude-imgid'])) { $att_ids = $_POST['jfiler-items-exclude-imgid']; $att_id = explode(',', $att_ids); foreach ($att_id as $atts_id){ wp_delete_attachment($att_ids); }
$att_ids = explode(',', $_POST['jfiler-items-exclude-imgid'])), will return a key=>value array, so you must write your foreach loop to handle keys and values foreach($att_ids as $key=>$att_id){ wp_delete_attachment($att_id); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, uploads, media" }
Modifying the Search Results I want to inject additional search results along with the search results provided by WordPress for the site search feature. Basically, I need to find the WP_Query object that the search uses, and modify it. I figure I should use the `posts_pre_query` filter, and return an array of post objects - some of which will be real post objects, and others which will be "fake" posts objects that represents results from the other sources. The problem I have is, how do I detect that this is a public search query - what characterizes a WP_Query instance that is a public search result?
add_filter( 'pre_get_posts', '__filter_pre_get_posts' ); function __filter_pre_get_posts( $query ) { // this is to detect a public search query if ( ! is_admin() && $query->is_search ) { // DO your magic here... } }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "wp query, filters, search" }
Plugin readme.txt and assets internationalization I've learnt how to internationalize my plugin, but that does not seem to cover documentation (readme.txt), screenshots and banners (assets). I'd like to present localized versions of those as well, is it feasible?
You can use the translation option via "GlotPress" on each plugin in the official plugin repository. You find all relevant hints in this post of the make blog at wordpress.org. In short, on each plugin you have a translation link and that give all users the chance to contribute translations.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "plugins, localization" }
Where am I gaining 6px height retrieving buddypress avatar I'm currently in the process of building a social network based site using buddypress and when the user is logged in I want to display their avatar in my header. To do this I've used this code. <div id="avatar"> <a href="<?php echo bp_loggedin_user_domain(); ?>"> <?php bp_loggedin_user_avatar( 'type=thumb&width=30&height=30' ); ?> </a> </div> It may seem like a small detail and something I can probably work around if I really needed to, but I would love to find out what was causing this seeming mysterious 6px gain I'm suffering from. You can see the site i'm working on by visiting www.vwrx-project.co.uk. I think you'd have to sign in, in order to see the avatar display, which your more than welcome to do. Once the theme development is complete I'll be erasing the entire database to start afresh after testing anyway.
The problem is with your line heights being set at 1.5. You need to set this in your CSS: #avatar { line-height: 0; } Also, if you want to get your other buttons "Logout" and the username, you will need to set the specific height on the parent DIV, which should be 50px, being as though your image is 30px, and you have 10px padding on top and bottom
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "buddypress" }
Preview returns 404 in theme I have a theme which appears to have broken previewing posts. When I preview a page/post I get a 404 error. If I change to another theme previews work fine again so it must be something in this theme. I can't work out when/if I would have broken previews. Going through my filters and actions I can't see anything obvious. Has anyone had a similar problem/ What did it turn out to be?
I found the answer. It was only for post-formats on pages. The issue was that I needed to also register the taxonomy `post_format` on pages as well in the init action. I have updated the wiki page to reflect this. < // add post-formats to post_type 'page' add_action('init', 'my_theme_slug_add_post_formats_to_page', 11); function my_theme_slug_add_post_formats_to_page(){ add_post_type_support( 'page', 'post-formats' ); register_taxonomy_for_object_type( 'post_format', 'page' ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development" }
Intercept the "lost password" action by first redirecting to an existing instructions page We have a situation where the users (children) keep not forgetting their password but making trivial mistakes while trying to login. As per question they should be first redirected to page e.g. id=5 with instructions like: > Please go back and: > Activate your cookies > Check if the correct language is on your keyboard > Ask your mother to log you in > etc... > If none of the above works please click here (< to ask for a new password So, the lostpassword link on the login page should redirect to the existing page with the custom message/instructions **and then** , the link on the page to the actual lostpassword link. _PS: I believe that the lately introducedlostpassword_post hook could be useful._
This is straightforward. 1. Hook on init to detect the lostpassword page 2. If the user is not coming from your instructions page (which we defined by adding extra query parameter) he'll be redirected to your custom page 3. In your custom page add the link to lost password page including the extra parameter we set to skip the redirection. add_action( 'init', 'lostpassword_instructions' ); function lostpassword_instructions() { global $pagenow; if ( $pagenow == 'wp-login.php' && isset( $_REQUEST[ 'action' ] ) && $_REQUEST[ 'action' ] == 'lostpassword' && ! isset( $_REQUEST[ 'skip' ] ) ) { exit( wp_redirect( ' ) ); } } Now on your custom page, something like that should work: $url = '
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "redirect, password" }
Can't figure out how to get space around an image? If you go to this page you will see the text is butted up against the right side of the headshot picture. I've tried plugins and codes, etc., but nothing seems to work. Any ideas on how I can get some padding around the picture so the text won't be right up against it?
If for just this image, you can edit that post and in text editing mode you could add something like this around the link to the image: <span style="float:left;padding:10px;"> ...<img>image link here... </span> If you are looking to fix this for any image that is added to posts, you'd need to add a rule similar to this to your .css for the theme you are using. Some themes allow custom css to be added, check the settings/options for your theme. img[class*="wp-image-"] { padding: 10px; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images" }
Templates dropdown not appearing using _s theme (underscores) I am currently using _s via < and am trying to add a new page template... I should be able to just add this new page template in the root of my theme, correct? Or should I be create a page-templates folder? I have tried something as simple as: <?php /** * Template Name: Front Page */ ?> But, the Templates selection dropdown is not appearing when I try to add a new page. Using WordPress 4.6.1 and Underscores.me most latest version.
It was a really trivial thing, in the end. My template file was not saved with a .php extension. It's always the little things!!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, templates, page template, dropdown" }
Is it possible to set custom post type revision limit inside the theme files? i want to be able to set the revisions limit number of a specific post type. i know there is a plugin for that, and i know it can be set through the "wp-config.php" file, but **my question is:** Is there a simple short code i can implement on my theme to do that without a plugin and without the need to change other files out of the theme folder scope?
I had a look at the `wp_revisions_to_keep()` function. There's a filter called `wp_revisions_to_keep` that overrides the value of `WP_POST_REVISIONS`. Here's an untested example ( _PHP 5.4+_ ): add_filter( 'wp_revisions_to_keep', function( $num, $post ) { // Post Types and Revision Numbers - Edit to your needs $config = [ 'post' => 10, 'page' => 9, 'cpt' => 8 ]; // Get the current post type $post_type = get_post_type( $post ); // Override the WP_POST_REVISIONS value if( isset( $config[$post_type] ) && is_int( $config[$post_type] ) ) $num = $config[$post_type]; return $num; }, 10, 2 ); But I think this kind of configuration would make more sense as a plugin than being theme related.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "revisions" }
To have Wordpress interact with memcached it must be installed as a PHP extension? I have the `Memcached` Daemon running on my server but some plugins for wordpress don't see it (i.e. W3 total Cache). Do I need to configure it as a PHP extension to use it? I've found this answer: W3 Total Cache doesn't detect memcached and this article < but some explanation would be very useful
This depends on what is it that you are trying to do/use. In theory the protocol used to communicate with memcached server is not very complex and can be implemented in PHP, and therefor as a plugin. In practice you might want to prevent collisions of multiple processes writing at the same time to the cahce which will most likely require the access to the multi tasking API of the OS, something that is not built-in in the default PHP modules and will require you to use additional modules in any case. (there is also probably some performance argument that can be made here between running C and PHP code, but I am not sure how important it is). Having it as module also let you as the server admin "break out" of whatever restrictions you put on the PHP code in the php.ini and other setting files (in theory you can block the ability of the PHP application to connect anywhere, although I never heard of anyone doing that)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "cache" }
Problem : deletion failed, the theme requested does not exist I had an awkward problem when i want to delete my theme, it gaves me this message: deletion failed, the theme requested does not exist wordpress. I can delete it from ftp manually but for client i want it to be deleted just from dashboard. Is any one have an idea how to resolve this error. ![enter image description here]( P.S. the theme works fine without any error.
I found what cause this problem, the theme folder shouldn't have any space if you had two words or more on it for example if your theme's name is : twenty sixteen it should be written without space in one word twentysixteen. So all i had to do is make my theme's name in one word and my theme was deleted normally from the dashboard. I hope it will help someone else.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 3, "tags": "themes, errors, customization" }
Get all users attached to a taxonomy I have created a taxonomy called "user_category" I am able to obtain the id of the term from the current logged in user - $current_user = wp_get_current_user(); $terms = get_the_terms($current_user->ID, 'user_category' ); With the id for this term, I then want to find all other users that have this same term id. I have the following, however this does not work, it will return a post - $args = array( 'tax_query' => array( array( 'taxonomy' => 'user_category', 'field' => 'term_id', 'terms' => 2 // This being the id ) ) ); $postslist = get_posts( $args ); Can someone help point me in the right direction?
You can use Wordpress function get_objects_in_term $users = get_objects_in_term(2, 'user_category'); // 2 being term id This return array of users that have this same term id.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, taxonomy, users" }
Can not using get_header() cause trouble (later on)? Can not using `get_header()` cause trouble (later on)? I can think of several reasons of not using `get_header()`, for example if you would be making a one page website or you want to use some other php templating system or you want your header.php to be in a subfolder. I know get_header() is basically the same as get_template_part() except for the fact that it does a `do_action('get_header')` (and uses require_once). So the real question would be can not having `do_action('get_header')` inside of your template cause trouble?
As long as the `wp_head()` function is still being called in the template, you should be fine. You've pretty much summed it up in your question; by not using `get_header()`, the `get_header` action will not be fired, but that wouldn't matter for your particular use case. Using `get_header()` along with the name parameter would be the more "WordPress way" of doing it though: `get_header( 'single-page-app' );` Would use the file `header-single-page-app.php`. `get_header()` uses `locate_template()` internally, which does not search sub directories, so this approach would not be suitable for your use case.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "hooks" }
Show custom post type under last posts configuration I am looking for a way to display a custom post type or posts on my main page, which should be configured under the last post type section in settings. I tried the following: add_filter( 'widget_posts_args', 'recent_posts_args'); function recent_posts_args($args) { $args['post_type'] = array('post', 'custom Post Type'); return $args; } Any suggestions what I am doing wrong? I guess it is the `widget_posts_args` argument, but I am not sure what else to use instead? I appreciate your replies!
replace `custom Post Type` there with your real custom post type name: $args['post_type'] = array('post', 'custom Post Type');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, posts" }
How to Add an Index to Plugin Database table I've created some additional tables for a plugin I'm developing and need to add indexes to these tables. What's the WordPress way to do this? Using `dbDelta()` doesn't seem to be working, and I'm not seeing any error in the logs.
You can execute _arbitrary_ SQL statements with wpdb::query(), including Data Definition Statements, e.g. function create_index () { global $wpdb ; $sql = "CREATE INDEX my_index ON {$wpdb->prefix}my_table (my_column)" ; $wpdb->query ($sql) ; return ; } **Note:** Because `$wpdb->query()` can execute _arbitrary_ SQL, if the statement you pass to it contains **ANY** user input, then you should use wpdb::prepare() to protect against SQL Injection attacks. But this raises the question: how did you create your plugin-specific tables? "Manually" or programmatically? If programmatically, did you not use `$wpdb->query()`? If you did it "manually", then you really should create the tables (and their indexes) upon plugin activation. See the excellent answer to this other WPSE question for how to hook into plugin activation (and/or deactivation and uninstall) to do things like create private tables.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 12, "tags": "plugins, plugin development, database" }
How can I place ad code after every 5 activities in BuddyPress activity loop? I tried to display ad code in BuddyPress every 5 activities. Can anyone suggest how this can be done? Here is what I've got so far: <?php while ( bp_activities() ) : bp_the_activity(); ?> <?php bp_get_template_part( 'activity/entry' ); ?> <?php $count = bp_get_activity_count(); for ( $i = 1; $i < $count; $i++ ) { if ( $i % 8 == 0 ) { ?> <?php the_ad(3860); ?> <?php } ?> <?php } ?> <?php endwhile; ?>
Here's where I would start: <?php $count = 0; ?> <?php while ( bp_activities() ) : bp_the_activity();?> <?php bp_get_template_part( 'activity/entry' ); $count++; if ( $count % 5 == 0 ) { the_ad(3860); } ?> <?php endwhile; ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "buddypress" }
AJAX response, edit tags Is it possible to customize AJAX response when using filters such as `check_admin_referer` and `check_ajax_referer` ? I've done some tweaks (with those filters) to prevent users from deleting some terms that are really important and MUST not be deleted. But it keeps telling me "unknown error" which is far from being clear. Any hint would be cool. For now I'm using wp_die( 'This term cannot be deleted' ) and I wonder how to inject this message in AJAX response.
Wait for WordPress 4.7 on 6th December. It has this almost built-in. If I got it right, then you'll want to prevent some terms from deletion. I already made a snippet for that which works with WP 4.7 add_filter( 'user_has_cap', function ( $allcaps, $caps, $args ) { if ( ! isset( $args[0] ) || 'delete_term' != $args[0] ) { // not the deletion process => ignore return $allcaps; } $term = get_term( $args[2] ); // HERE YOU'LL LIKE TO PUT YOUR LOGIC INSTEAD OF THIS: if ( $term->count <= 0 ) { return $allcaps; } // for all other cases => reject deletion return [ ]; }, 10, 3 ); For more details read <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom taxonomy, ajax, terms" }
im trying make a function to auto correct posts when i open the posts in the backoffice I have a area where users can submit posts however the posts usually contain a lot of errors and i'm trying to create a function that auto-corrects this errors when I open the post in the back office, it doesn't work: function processpost( $processpost) { $errors = array("oly"); $processpost['post_content'] = str_replace($errors, 'only',$processpost['post_content']); return $processpost; } add_action('pre_post_update', 'processpost', 99);
Ahh, you're using the wrong action - you need: add_filter( 'wp_insert_post_data', 'processpost' ); View `wp_insert_post` source
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, functions" }
the_tags outputs before echo The following very simple snippet of code is not working right: the tags are being displayed in the page, but outside of the span with class "tags". echo '<span class="tags">' . the_tags('See also: ', ' &middot; ') . '</span>'; Here's the output: See also: <a href="#" rel="tag">animals</a> · <a href="#" rel="tag">communities</a> · <a href="#" rel="tag">cultural differences</a> · <a href="#" rel="tag">projects</a> <span class="tags"></span>
`the_tags()` doesn't return the links but immediately echoes them. As that happens before the `echo` they appear before the span. What you want is this: echo '<span class="tags">'; the_tags('See also: ', ' &middot; '); echo '</span>'; or even simpler the_tags( '<span class="tags"> See also: ',' &middot; ', '</span>' ); As a general rule of thumb you can remember that function that start with `the_` directly echo things, while functions starting with `get_` return stuff. So here you could also be using this: echo '<span class="tags">' . get_the_tag_list('See also: ', ' &middot; ') . '</span>';
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "tags" }
writing posts in indian regional language (Punjabi) I am trying to create a post in Punjabi Language . But when i try to paste punjabi text into the editor , the language automatically gets converted to English. I tried using the Google Translator plugin , but that does not convert the page accurately. Is there a way i can post articles in regional language ?
If you want to install WordPress and use it in Punjabi, there is an ongoing effort to localize WordPress into Punjabi; see < The support forums in Punjabi are not yet complete: < > I tried using the Google Translator plugin, but that does not convert the page accurately. Google Translator is machine translation, not human; it won't be accurate to a native speaker. And, that's a completely separate issue than actually using WordPress in Punjabi, i.e. entering text in Punjabi in the Wordpress editor. If you want to post Punjabi text in a WordPress site installed in another language (like English), you can paste Punjabi from Google Translate < and have it render correctly in WordPress. (I tried this myself). If it doesn't, something is wrong. It might be worth contacting the translation team <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, custom content" }
How to get site URL if database is disconnected? Recently I realized that you could include a db-error.php file in your `wp-content` directory from "How to monitor server for error establishing a database connection" that would replace the existing WordPress database error message with something custom. I thought about doing a redirect in db-error.php like: header("Location: exit(); but I wanted to replace ` with the site URL so this could be portable but after researching I didn't see a way to obtain the site URL without the connection and I per discussions I was told you want to do minimal modifications to the wp.config file. Is there a way to get the site URL without a database connection that could be used in the header redirect?
One option is setting the site's URL in the `wp-config.php` file itself. This effectively overrides the `siteurl` option that's otherwise stored in the database, but it also means you can reference the URL without doing a query. From the Codex: > It is possible to set the site URL manually in the wp-config.php file. > > Add these two lines to your wp-config.php, where "example.com" is the correct location of your site. > > > define('WP_HOME',' > define('WP_SITEURL',' > After that, using code in a regular theme that checks the `siteurl` or `home` option will pull from the constant rather than the database (hence my note on the override above). But in your default error script, you can reference `WP_SITEURL` directly to build a redirect URL.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "database, redirect, debug" }
Redirecting /px/?q=x to /px/x/ We have a page that displays products depending on a query string variable `q`. Like this: We would like to display the URL of such pages like this instead: So far we haven't been able to make it work, so does any of you have some ideas? * The solution can be in `.htaccess` or in `functions.php` (we have a child theme). We are happy as long as it works * Our page that displays products has nothing to do with normal WordPress searching. It's just a normal WordPress page that changes content based on the URL (i.e. what comes after `/px/`)
In your `.htaccess` add the following rule in between the `<IfModule mod_rewrite.c>` tag: RewriteCond %{QUERY_STRING} ^q=(.*)$ [NC] RewriteRule ^/?px/(.*)$ px/%1? [L,R=301] Based off of the default `.htaccess` generated by WordPress, it should now look like the following with your custom `RewriteRule`: <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] # Custom Rules RewriteCond %{QUERY_STRING} ^q=(.*)$ [NC] RewriteRule ^/?px/(.*)$ px/%1? [L,R=301] </IfModule> Clear your browser's cache and any domain that follows this structure: Will redirect to: This has been verified and tested on my end using the htaccess tester.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "url rewriting, redirect, htaccess" }
Best way to find all shortcodes that come with WordPress I am using WordPress 4.6.1. What tactics can I apply to find all available shortcodes that come with WordPress OOTB. I am having trouble find this information on the web. various guides in the codex and outside of it use simple examples like [gallery], but I am curious to knowing what is my full available list. Thanks
You could grep the 4.6.1 core codebase for all instances of "add_shortcode". Alternatively, there is an extension for Debug Bar that will show you all shortcodes: <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "shortcode" }
How to modify Media Library images How can I modify the size at which images in the media library are displayed when viewing the media library? I use a function to disable generation/modification of images, and manually edit to 750x250px then upload. When viewing the media library, I want them to display in this rectangular format _(although smaller than actual)_ rather than the default square.
A quick look at the media page with Firebug shows that this CSS statement will allow you to change the size of the picture: .media-frame-content[data-columns="9"] .attachment { width: 11.11%; } Change the 'width' value to something different, with the understanding that the change may affect how the page looks on different size screens. You should put your modified CSS in the styles.css of a Child Theme, since any updates of WP or the theme (which might have their own media page) would cancel out your changes.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "media library" }
Auto Complete Search I have a post type name jobs and I created a few custom taxonomies named 'region', 'job_type' now I want to create a search that uses the custom taxonomies and jobs post types. I want the search to have an auto-complete feature. Any help or direction would be great.
I solved the problem using this plugin
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, custom taxonomy, search" }
Multiple editable areas I am new to WordPress development and I am editing an existing theme. Basically, I created a custom template for Pages. I learnt that the editable content of the template is defined by the the_content() function. The problem is that I want to have more areas for the user to add content. Is that possible? here's is an example: <div class="row"> <div class="col-md-12"> <div style="mystyle"> <div class="center-block " style="someotherstyle"> // i want text here <?php the_content(); ?> // this works </div> </div> // want also content here // tried the_content() but it's not working twice. </div> </div>
You can add more meta boxes - with simple text field editors or TinyMCE editors with more functions - in admin, and then call those meta boxes in your page template. This is a very common thing to do in WordPress, both in a UX sense for the user to be able to add content, and because - as you have discovered as a site admin and theme developer - the function `the_content()` can only be used once in the loop and wasn't designed to be used multiple times. Best thing to do is take a look at some plugins that enable you to add and configure the display of more meta boxes. The most popular and extensible is < And do a search for other similar questions: < regarding that plugin.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development" }
Permalinks Messed up I am trying to fix a problem, the links are all messed up and look like ![enter image description here]( I have tried this code in the public_html folder in a .htaccess file, the links are now working with index.php/%postname%/ but I need to get rid of the index.php # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress Any Help would be amazing. Thanks
After hours of searching and reading, This is how I solved the Problem. Step 1: Create a .htaccess file in the root folder and put this code there. # BEGIN <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END Step 2: is Mentioned here ![enter image description here](
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "permalinks" }
Custom query var rewriting with only variable On every post there is a "read" (default) and "listen" button that users can click on without page refresh. The listen tab can be accessed directly through domain.com/category/post-title/?listen=listen and domain.com/category/post-title/listen/listen I would like to edit the rewrite rule so that the same page can accessed though domain.com/category/post-title/listen How would I go about doing this? My code: function cp_narrations_query_vars( $qvars ) { $qvars[] = 'listen'; return $qvars; } add_filter( 'query_vars', 'cp_narrations_query_vars' , 10, 1 ); function cp_add_my_endpoint(){ add_rewrite_endpoint( 'listen', EP_PERMALINK ); } add_action( 'init', 'cp_add_my_endpoint' );
Answered thanks to Milo's comment. I wrote a small function to check if the query variable exists. Note that `get_query_var('listen')` didn't work for me. function is_listen() { $vars = $GLOBALS['wp_query']->query_vars; if ( array_key_exists('listen', $vars) ) { return true; } else { return false; } } Use it in a conditional like so: if ( is_listen() ) { // Display listen tab }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "permalinks, rewrite rules, query variable" }
Are custom post types suitable for storing high numbers of data elements, in this case chat messages? I'm developing a system that will have around 2k users and they will be communicating with an internal live chatting system. Now I'm wondering if it's a good choice to store messages as custom post type? Or it's better to use custom table for them?
As far as I can see, the main problem you might have to deal with is having to store a fairly large amount of chat messages. So to avoid making WP core functionalities querying post and postmeta from large amount of rows generated by your single functionality, it seems obvious to me you'd better create a custom table. I believe this would also offer to you the possibility to optimize your table's structure for your specific usage which would result in faster queries. **At this time** , WP postmeta queries get very slow generally speaking, when they have to deal with a large amount of rows. Look at the problem WooCommerce actually has when dealing with over 100k products which they store as post and postmeta. They're on the way of fixing this by migrating all the products inside custom tables...
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "custom post types, table" }
Remove header title form page through CSS I would like to change the size of the message on my shopping-cart page, for example: < If a product is added, there a large message appears ( _Winkelwagen_ ). I messed around with inspect element and got rid of the extra space, but I'm not versed in coding enough to get the right code in the `style.css` file of my child theme. Is there any way I can simply get rid of the following for that page? <div class='c12 end pageheading'> When I play around with it in the inspect element the problem disappears. Does anybody have suggestions?
To hide the title ( _Winkelwagen_ ) from that page: ![]( This is the CSS that you want to run: .c12.end.pageheading { display: none; } You can add that to your child theme's `style.css`, or you can add the following to your child theme's `functions.php`: add_action( 'wp_head', 'hide_winkelwagen' ); function hide_winkelwagen() { ?> <style itype='text/css'> .c12.end.pageheading { display: none; } </style> <?php } Either one will give you the same result.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization, css" }
$wpdb Mysql trigger problem This is an extension of this question : SO I want to implement the mysql trigger helpfully provided by @Shadow into a Wordpress plugin. The query=trigger is $sql_trigger = " drop trigger if exists bi_tbl_B $$ delimiter $$ create trigger bi_tbl_B before insert on tbl_B for each row begin DECLARE v_slug as varchar(255); DECLARE v_url as text; SELECT url, slug INTO v_url, v_slug FROM tbl_A WHERE id = NEW.id; NEW.url=v_url; NEW.slug=v_slug; end; $$ delimiter ; "; mysqli_multi_query($wpdb->dbh,$sql_trigger); I have few questions: 1) Is this query correct or I need to make changes? 2) Do I have to use any one of this `global $wpdb;` or $mysqli = new mysqli(); $mysqli->connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); 3) Is the query safe?
1. No idea 2. yes, use `$wpdb` 3. seems like it should be. OTOH if this is something you want to do in a plugin, I am not sure if normal wordpress users (as defined in the DB) have trigger creation privilege. just be careful with what you are trying to do, as if you have object caching and the data you create is read by wordpress APIs, you might end up with a mismatch between the cache and the DB.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, mysql" }
List child pages within page template I am building a page template within a theme that lists child pages for a product page. Is it possible to change this so that it lists the children of the page the user is on rather than having to specify a page ID? My code <?php $args=array( 'post_parent' => 27641, // This page! 'post_type' => 'page', ); $my_query = null; $my_query = new WP_Query($args); if( $my_query->have_posts() ) {?> <ul> <?php while ($my_query->have_posts()) : $my_query->the_post(); ?> <li> <a href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>" itemprop="url"> <?php the_title_attribute(); ?> </a> </li> <?php endwhile; } ?> </ul> <?php wp_reset_query(); // Restore global post data stomped by the_post().?>
The ID of the current page is available via the global $post variable, so to get the ID use: global $post; $currentPage = $post->ID; Then you can use $currentPage in your query :)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "pages, templates, id" }
Replace post's "the_content" with ACF value I try to replace post's `the_content` with value from ACF field `article_text`. I managed to achieve it with following method: $postid = get_queried_object_id(); $my_post = array( 'ID' => $postid, 'post_content' => get_field('article_text'), ); wp_update_post( $my_post ); the_content(); But I have a small issue with it: when I create post, `the_content` doesn't automatically gets the value from ACF `article_text`. I have to refresh the browser couple times in order to see that change. When I preview the post without publishing, I cannot see `the_content` at all. My question - is there a more efficient way to do it to see the content straight away? The reason why I want to display `the_content` instead of `article_text` is because of several not-ACF-friendly plugins.
Instead of updating the post's content, you can filter it using the `the_content` filter. add_filter( 'the_content', 'wpse241388_use_acf_field' ); function wpse241388_use_acf_field( $content ) { return get_field( 'article_text' ); } ## Update To apply to only your `article` post type: add_filter( 'the_content', 'wpse241388_use_acf_field' ); function wpse241388_use_acf_field( $content ) { if ( is_singular( 'article' ) ) { $content = get_field( 'article_text' ); } return $content; } ## References * `the_content` filter * `is_singular()`
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "advanced custom fields, the content" }
Can we have private drafts? As per the documentation, Draft and Private are two mutually exclusive post statuses. Therefore, when you mark a draft post as Private, it is no longer a draft. We are a big team making extensive use of private posts. Therefore, we would like to mark a draft as private (an unfinished post that will be internal). Ideally, the "publish" button would un-draft the post, not make it public. To put it differently, we need both a (draft / finished post) distinction, and a (public / private post) distinction. Is that possible? Do we need a custom post status?
I would probably create a custom field / check box for this for a draft stage. Then hook into post status transition (or around) and when post is published force it to only private, even if normal publish was pressed. From personal experience custom post statuses are a wreck. They _seem_ like a good idea, but they just introduce mountain more of access and visibility problems since core code never cared much for any non–default status.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "publish, private, draft" }
wp-cli regenerate media is not working for custom sizes I'm using `wp media regenerate` to generate thumbnails. While this works for the built-in Wordpress image sizes (even when the width and height are customized in `functions.php`), it does not work at all for custom image sizes. The command finishes and the custom sizes simply are not generated. The original images are much larger than the sizes being generated, so it's not related to upsampling. I've also tried declaring the custom sizes using the `after_setup_theme` action hook, but the result was the same. Does `wp media regenerate` only work for the built-in media sizes, or am I doing something wrong? **functions.php** // Built-in sizes work update_option("large_size_w", 2000); update_option("large_size_h", 9999); update_option("large_crop", 0); // Custom sizes don't work add_image_size("Custom Size", 320, 320, true);
I finally figured this out. It ended up being something really stupid. I have short tags enabled on my server so I can use `<?` instead of `<?php` in theme files. I was also using a short tag to open my `functions.php` file. Apparently, when PHP scripts run from the command line, they require the full `<?php` open tag, otherwise they just echo to the console. I made this change in my `functions.php` file and it works now. By the way, if this is useful to anyone else, I wrote a Node.js script for processing massive WordPress media libraries that leverages as many cores as you have (in my case, 32 cores). <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "post thumbnails, images, wp cli" }
WpAlchemy - _global_head is being output 3 times Today while attempting to make use of the repeating fields function (have_fields_and_multi) I've discovered that with the latest WpAlchemy (1.6.1) and the latest Wordpress (4.6.1), the inline JavaScript blocks from MetaBox.php are output 3 times on the admin page. This breaks functionality because 3 sets of onclick events are included. I tried this on two local sites with the same result. I'm attempting to work around it via event.stopImmediatePropogation as a temporary fix but would love to have something more solid. (I have added this as an issue at < as well) Am I'm alone in experiencing this problem, and does anyone have any idea how to fix it?
The clue was in the original script here - line 460 of MetaBox.php has the comment "// todo: when first run define a constant to prevent other instances from running again ...". The code below fixed this issue. if(!defined('HEAD_CALLED')): add_action( 'admin_head', array( $this, '_global_head' ) ); define('HEAD_CALLED', true); endif;
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "wpalchemy" }
Do my defines need to be unique? In the root file of my plugin (`the-plugin/the-plugin.php`), I've set up some defines that I will be using throughout my plugin: # Plugin's latest version define( 'THEPLUIGN_VERSION', '2.0.0' ); # Minimum WordPress version required define( 'THEPLUIGN_MIN_WP', '3.7' ); # Minimum PHP version required define( 'THEPLUIGN_MIN_PHP', '5.3' ); # Plugin base define( 'THEPLUIGN_BASE', plugin_basename( __FILE__ ) ); As you can see, I've prefix the defines with `THEPLUGIN_`, I assume this is necessary to add in order to keep each of the values unique and to prevent conflict with other plugins. Is this true? Or is there a better way to define these values, globally, to be used throughout my plugin? I've implemented both namespaces and class structure in my plugin.
Yes they do, the more interesting question is why do you use define instead of `const`? Take a look here: define() vs const. The only situation in which you should use a define over `const` is if you want the user to be able to override your defines in `wp-config.php`. Obviously things like minimum php version should not be overridable. Once you go with const you can just use namespaces and get over the whole issue. The only problem is that const before PHP 5.6 could not be assigned an expression and you have two defines which are not simple values. If you target PHP 5.6 and above then, in my opinion, just use `const`. Otherwise defines should be avoided as they can be overwritten by mistake, but it is your judgment call about using defined values instead of calling the relevant APIs.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, plugin development" }
Disable to create folders for every years and months in uploads folder How can I disable to create folders for every years and months in uploads folder? I mean there is a lot of folder under "wp-content/uploads", and the majority of them are empty. Why create WP these folders? Thanks!
You can disable this by going to **Settings -> Media** ![Media Settings]( If you uncheck the setting all the **future** media uploads will directly into `wp-content/uploads` folder. > Why create WP these folders? WP doesn't create empty folders, I assume those folders are created when you have uploaded media and now they they are empty because you might have mass deleted media files for those months. WP doesn't delete folder once there are no media files(I mean once you have deleted all corresponding media files). * * * My opinion is that it's not a big deal that even if we have empty folders.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "directory, uploads" }
How to Backup and Transfer Everything to Another WordPress Site? After doing much research, I give up and finally decided to ask this question here. I have created a WordPress Theme locally on my computer, and I want to transfer everything (database, posts, pages, plugins, custom fields, custom post types, media etc.) to another WordPress site. Here what I did, but it is not working out for me, and I am not sure what I am doing wrong, I have backed up my SQL database and upload it to the database of my new website. I also backed up my posts, pages etc. using the default WordPress plugin, and also upload it to my new website. Not sure what I am doing wrong, but it did not restore a thing. So, my question is what is the best way and the easiest way to backup and transfer everything in WordPress? P.S. These are the three plugins that I used to backup everything, BackUpWordPress, Migrate DB, and the default WordPress Import/Export Plugin.
I use All-in-One WP Migration and it works perfectly every time. A lot of site configuration information, including URLs, is stored in the database and this plugin is pretty good at figuring out how to make the necessary changes, including where info is serialised.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "backup, migration" }
Font-Family does not looks like how it should be I have been trying to put my font-family to Clarendon Lt BT Light, but it has been reflecting New Times Roman to me. This wasn't an issue to me until now. I placed this at the top of my CSS file.: @font-face { font-family: 'ClarendonLtBtLight'; src: url(../fonts/ClarendonLtBtLight.ttf); } This is how I apply it to my webpage: nav.main_menu > ul > li > a { color: #686868; font-family: 'ClarendonLtBtLight'; font-size: 18px; font-style: normal; font-weight: 600; text-transform: uppercase; letter-spacing: 1px; } I had also place the .tff place to the correct directory. Please advice.
This might be a reference error. Try opening the developer console on your browser as you load the page. See if you can find errors such as: "NOT FOUND", etc.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, css, html" }
How to change footer or <div> for different kinds of users in wordpress? I am planning to make a website where non website members should see a different view of the footer. Is this possible using css only?
When a user is logged in, WordPress adds the class logged-in to the body tag, so you can target CSS differently for logged in users. body > footer { background: black; } body.logged-in > footer { background: red; } for example. This is only good for cosmetic changes though. Don't try to use it to hide information from non-logged in users as the content is still in the HTML.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "theme development, css, user roles, user access, footer" }
Functions - callback vs fallback While seeing the source code of some themes or plugins, I have noticed that, sometimes these two words are used to denote/indicate other functions. What's the difference between them? Which function should be called `callback` function and which is `fallback`? Can you give me an example? Thanks in advance.
That is not really a question in the focus of WordPress, is also in other programming languages and in our speaking language a topic. Maybe I can clear the difference between these words with a non coding example. ## Callback A return of a situation to a state. Like a call with the telephone to a message of the phone or the answering machine to a defect of a product. In the coding context is a callback a function/method which executed after the current effect is finished. ## Fallback An act of falling back. Like an alternative plan to the current idea, progress. In context of the computer is a fallback typically a backup of the current data to fallback to a time stamp.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "functions" }
My custom made plugin has "a new version available" which links to unrelated plugin My custom made plugin has "a new version available", also the "view details" link links to a completely unrelated plugin. The plugin files begins with: <?php /* Plugin Name: Simple Contact Form Plugin URI: Description: Simple contact form Version: 1 Author: Wilco Verhoeven Author URI: */ How can I prevent this?
I think you've got a naming conflict there -- assuming that your plugin is linking to this Simple Contact Form -- try changing the name to something like "Wilco's Simple Contact Form". You'll need to update the plugin folder name and the main plugin file name as well. **Update** As Aniket points out, you might need to force an update check on your site to get rid of the notice. You can do this by going to `
stackexchange-wordpress
{ "answer_score": 13, "question_score": 7, "tags": "plugins, plugin development" }
AddFilter option_active_plugins is executed 6 times. Why? I've put an adsense script in the `mu-plugins` folder, hooked it to the `option_active_plugins` but it happens to be executed 6 times. Is it an error?
> is it "strange" that this hooks is called more than once? No, not at all - this filter will fire anytime `get_option( 'active_plugins' )` is called, which almost certainly happens multiple times per request.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "plugins, hooks" }
Edit post_content on posts with Featured Image Great forum! I'm a total newbie to SQL but a quick learner. I have a large database of content, >140k posts. Some posts have Featured Images, others do not. I would like to edit post_content on posts with Featured Image. I do not need to know anything about the Featured Image, only that the post I edit has one and is not null. I would basically like to do a simple search and replace in post_content on posts with a Featured Image. I do not want to edit posts that do not have a Featured Image set. Thank you for any help you can provide.
I would do this as follows: 1. Back up the entire DB (or certainly the wp_posts table!) 2. Run this query to get all posts that have a featured image: SELECT wp_posts.* FROM wp_postmeta INNER JOIN wp_posts ON (wp_postmeta.post_id = wp_posts.ID) AND meta_key='_thumbnail_id'; 3. Export the results to a plain SQL file with SQL inserts 4. Do your search and replace within that SQL file 5. Reimport the data. This assumes your tables have the default prefix obviously.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 2, "tags": "meta query, sql" }
WooCommerce show decimals in totals Learning PHP and a little stuck on a fairly straight forward issue. I am trying to edit my WooCommerce invoice This code `<?php echo $sign.number_format($order->get_subtotal(),2); ?>` Returns $50.98 This code `$first_number = $order->get_subtotal();` Returns a variable of 51, it rounds up as the `,2` is missing. How do I add `(),2;` to the above code so it returns that variable just as a number with decimals so i can make calculations with it. If I try this`$first_number = ($order->get_subtotal(),2);` It breaks as I obviously don't know the correct syntax. Thanks for any pointers
Try $first_number = number_format( $order->get_subtotal(), 2 ); number_format() is the php function that is setting the decimals in your first bit of code above. See <
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "woocommerce offtopic" }
WP-CLI Bulk delete posts from specific category I would like to know how to bulk delete posts from a specific category using the WP-CLI, any tip?
This should delete **all** posts in your category: wp post delete $(wp post list --cat=your_category_ID --format=ids) **Or** directly: wp db query [<your_sql_query>] For more info: wp post delete --help wp post list --help wp db query --help
stackexchange-wordpress
{ "answer_score": 13, "question_score": 4, "tags": "posts, wp cli, bulk" }
Only get post_id I have a get_pages() function. I all works great but I only want all the post_id's in my variable. Is that possible? Thanks in advance. $countries = get_pages(array( "hierarchical" => 0, "sort_column" => "menu_order", "sort_order" => "desc", "meta_key" => "page_type", "meta_value" => 2, ));
Quick shot: $countries = get_pages(array( "hierarchical" => 0, "sort_column" => "menu_order", "sort_order" => "desc", "meta_key" => "page_type", "meta_value" => 2, )); $page_ids = array(); foreach ( $countries as $country ) { $page_ids[] = $country->ID; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, id" }
Shortcode in shortcode: How to append variable? In below example, I wrapped `[contact-form-7 id="33"]` inside another shortcode `[myform]`. So, when posting, just use `[myform]` istead: function wrapthecode() { return do_shortcode('[contact-form-7 id="33"]'); } add_shortcode( 'myform', 'wrapthecode' ); But how to append variable ID on the new shortcode? Means `[myform id="33"]` is `[contact-form-7 id="33"]` and `[myform id="34"]` is `[contact-form-7 id="34"]`
You need to get the attributes of the shortcode, which is quite simple and documented in the `add_shortcode()` examples: function wrapthecode( $attr ) { if( empty( $attr['id'] ) ) return 'No ID given.'; return do_shortcode('[contact-form-7 id="' . $attr['id'] . '"]'); } add_shortcode( 'myform', 'wrapthecode' );
stackexchange-wordpress
{ "answer_score": 8, "question_score": 5, "tags": "shortcode" }
Get media url (featured image) with wp-cli I am attaching an image to a post with the media import command. I know I can get the image id using the --porcelain option, but how can I get the image url from this id? Or is there a way to display the featured image's url of a post (apparently the list command does allow this)?
Assuming the attachment ID were in a variable of `$attachment_id` you could use the following command: # get attachment URL wp db query "SELECT guid FROM $(wp db tables *_posts) WHERE ID=\"$attachment_id\"" | head -n 2 | tail -1 I use the `$(wp db tables *_posts)` bit just in case the `wp_` table prefix is non-default.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp cli" }
How can I make a shortcode from this code? I've been using the code below to count items in a directory and then, by using a plugin, add it to a WordPress page. $dir = '/PATH TO DIRECTORY/'; $filecount = 0; $d = dir($dir); while ($f = $d->read()) { if(($f!= ".") && ($f!= "..")) { if(!is_dir($f)) $filecount++; } } echo '(',$filecount,')'; Wondering whether I can make a shortcode from it, I've pre-pended it with function item_count() { And appended it with: } add_shortcode('count', 'item_count'); But the echo is triggering a 'headers already sent' error. I've since learned that shortcodes should 'return' rather than 'echo', but haven't been able to figure-out what I need to do to use this as a shortcode.
It should be as simple as this: function item_count() { $dir = '/PATH TO DIRECTORY/'; $filecount = 0; $d = dir( $dir ); while ( $f = $d->read() ) { if ( ( $f!= "." ) && ( $f!= ".." ) ) { if( ! is_dir( $f ) ) { $filecount++; } } } return '(' . $filecount . ')'; } add_shortcode( 'count', 'item_count' ); If that's still giving you a Headers Already Sent error, then check to make sure that there's no whitespace at the end of your PHP file. (You can safely omit the closing `?>` tag, which will help you ensure that there's not any extraneous whitespace.) See this answer for more on omitting the closing PHP tag.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "shortcode" }
DB Sync Media Files extension I've installed WP DB Sync (master branch) in three different WP instances. I've also installed the WP DB Sync Media Files extension (master branch), however the "Media Files" checkbox is not showing up in the backend. I've also opened a issue at github, but no reply so far. Is there anything special I should do to make the WP DB Sync Media Files extension work, beyond unzipping it in the plugins folder and activating it?
Yes, there's another required step: I must enter the correct connection informations before the checkbox shows up. The JS code checks for the connection, talks to the remote plugin and if it finds it's all ok, lets the checkbox display itself. In other cases it hides the checkbox. Now I believe this plugin has a weird design, because implementing in JS (client side) a server-to-server migration is at least a strange choice, but that's another pair of shoes.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, sync" }
plugin translation is not working im working on translating a wordpress theme, i have translate all the language files even the related plugins files but then when i apply on my theme the words in my plugins langage files are not translated while the words located in my theme langage file are translated; here is a screenshot of one page that show the issue ![enter image description here]( here is a screenshot of the plugin language folder ![enter image description here]( and this is for theme language folder ![enter image description here](
i have fix this just put renaming the languages files in the plugin to `realia-ar.po` and `realia-ar.mo`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, translation" }
How to sort a table of custom posts by column containing custom field I have a custom post type called `laptop` with custom fields such as `CPU`, `OS`, `RAM` etc. creatied using the `Advanced Custom Fields` plugin. I'm displaying a table of laptops, where the table header is a row of custom fields, and each following row is a laptop name and it's custom field values in each of the corresponding column cells. I want to be able to sort the table by clicking on the table `TH` cell containing the custom field name. I've been pointed to meta query clauses by ACF support, but I'm out of my depth with those. I'd really appreciate some help in generating URLs to wrap around the the custom field name in each `TH` element.
To follow up on @rock3t's comment, do you really have to query the backend whenever a user clicks on a column header? Have you looking into using the jQuery tablesorter? It allows an end-user to sort an HTML table by doing DOM manipulations. I've never used it in a WP project, but I have used it extensively in other projects I've built and it works great. It's **very** configurable, so I'm sure it will satisfy your needs. tablesorter is **not** one of the jQuery plugins included with WP Core. So you'll have to download it (from the above link), include it in your plugin/theme somewhere and enqueue it. Then, enqueue a simple JS file that would like something like: (function ($) { $(document).ready (function () { $('#id_of_your_table').tablesorter ({widgets: ['zebra']}) ; }) ; })(jQuery) ; You can read more about how to use tablesort in their docs, including various other parms to the `tablesorter()` method.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "custom post types, custom field, advanced custom fields, sort" }
How to list categories by page id in wordpress I want to create a sidebar with below hierarchy. * All courses, * padi courses (these are pages) * \---divetravel (these are categories) * \---suba courses (these are categories) Can someone help me out because I could not able find any solution yet. I found get_category function but it will take post id as parameter. But I want to display categories related to that page.
You don't need to do any programming for something as simple as this. On the menu page, create a menu with these links. Then on the widget page, use the menu widget that comes with WP to add it to your sidebar.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, menus, widgets, sidebar, categories" }
How to delete an user including data from custom database tables Is it possible to remove an user from within the back-end including all data related to this user even from custom tables? I used the `add_action( 'delete_user', 'my_delete_user' );` hook and also execute a delete query to delete data from a custom table (related to that user) but only data from the **user** and **user_meta** table is deleted, not from the custom table. I would like to be able to delete _all_ data related to an user.
> Hello guys! > > i resolved this issue by using same hook add_action( 'delete_user', 'my_delete_user' ); > > here is my code <?php function my_delete_user( $user_id ) { global $wpdb; $user_obj = get_userdata( $user_id ); $id_user = $user_obj->ID; $idsss = $user_obj->user_id; /*Delete Data from friend table*/ $query_friend= $wpdb->query("DELETE FROM `wp_user_friends` where `friend_id` = ".$user_obj->ID.""); /*delete data from group*/ $delete_group_table =$wpdb->query("DELETE FROM `wp_group` where `user_id` = ".$user_obj->ID.""); } add_action( 'delete_user', 'my_delete_user' ); ?> > Now it's working perfect.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugin development, hooks" }
Redirect short-form URL to long-form URL (post_id to post_id + post_name) My blog uses this custom structure for permalinks: > /%post_id%/%postname%/ > > e.g.: < Articles can then be accessed and linked to in two ways: * Short form. e.g.: < * Long form. e.g.: < * The canonical URL (set with `<link rel="canonical">`) is the long-form URL. This is handy because, this way, links are shorter. Useful for sharing on Twitter. What I'd like to do, is **create a redirect from the short-form URL to the long-form URL.** My question is: where to do that? As I understand it: * `add_rewrite_rule` is not appropriate -- I cannot access `post_name` from it. * `add_permastruct` is not appropriate either -- I cannot declare a redirection in it. I guess I should create a hook somewhere, but where?
I think can do: add_action('template_redirect', 'my_func'); function my_func(){ if(is_single()){ // catch the last string preg_match('/(.*)\/(.*?)\//', $_SERVER['REQUEST_URI'], $new_array); $last_phrase= $new_array[2]; if(is_numeric($last_phrase)){ $id = $last_phrase; header('location: '. get_permalink($id) , true, 301); exit; } } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "permalinks, redirect, rewrite rules" }
Missing page on wordpress "Pages" dashboard I just put up a new site (< and was starting to add the base pages. I think something may have went wrong as I have 5 pages on the navigation bar, but only 4 pages on the Pages Dashboard. I am missing the "Home" page that I created from the dashboard. Any ideas on what could cause this or how to remedy? ![Missing pages](
The "catch-base" theme was the culprit. `Appearance > Customize > Static Front Page` then had to set the options for the Front page and the extra "Home" button went away. Thanks!
stackexchange-wordpress
{ "answer_score": 0, "question_score": -3, "tags": "pages, dashboard" }
How to create a front end user profile with a friendly permalink and a 404 trigger I've implemented the accepted answer from this question and works great: How to create a front end user profile with a friendly permalink But it does not trigger a 404 if you just enter anything /user/asdasd I'm thinking it needs to happen at some point in this section of code: if ( array_key_exists( 'user', $wp_query->query_vars ) ) { include (TEMPLATEPATH . '/user-profile.php'); exit; } So check the query_vars then maybe run that through the users database to check? I'm not really sure how to integrate a 404 redirect if the url is not a user. Maybe it is something that I put on user-profile.php to check if it returns anything about the user, if not, load the 404 template?
I believe the solution here would be as simple as you've generally described it. Assuming conveniently that `$wp_query->query_vars['user']` contains the **username** and not its **ID** : if ( array_key_exists( 'user', $wp_query->query_vars ) ) { if ( username_exists( $wp_query->query_vars['user'] ) ) { include( TEMPLATEPATH . '/user-profile.php' ); } else { include( TEMPLATEPATH . '/404.php' ); } exit; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "url rewriting, users, 404 error, front end, profiles" }
Can I Hook Into the TinyMCE Insert/Edit Link Button to Use Shortlink For Post? The idea here is to be able to use the Link button to search through posts as usual, but, once selected, use the shortlink (with something like `wp_get_shortlink();`) instead of the permalink: `<a href=" Link</a>` Not sure if it would be easier to add this function to the existing button or add a new button with this dedicated behavior.
If you mean the _link dialog_ , then we can modify the _permalinks_ with the `wp_link_query` filter: add_filter( 'wp_link_query', function( $results ) { foreach( $results as &$result ) $result['permalink'] = wp_get_shortlink( $result['ID'] ); return $results; } ); where we use `wp_get_shortlink()` to get the _short links_.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, hooks, actions, tinymce" }
Impossible User Registration I do have a client wordpress site in which I am the only one who have the Administrator login account. The client website doesn't have any registration form or any widget that allows any user to register. I even disabled the "Anyone can register" on the General Settings. But how come someone still manage to register an Admin account and eventually deleted and remove my Admin login credentials at the end. Could anyone help me explain how did that happened? Thank you very much.
Even if you disable registration, if the server has WP-CLI installed and if someone has ssh access then an admin user can easily be created using following command: `wp user create bob [email protected] --role=administrator` Thus, that admin user can login and remove other user account easily. ![Creating Admin User with WP-CLI]( Check this to know about all the possibilities through WP-CLI commands.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "wp admin, login, user registration" }
WP API Get post with tag names instead of tag ID's When you request posts using WP API's search mechanism, it returns tags as one of the post's properties, but it is an array of tag IDs, not tag names. Is there a way to make the API include the name of the tags without making subsequent requests to the API by tag ID for each one? tags: [ 188, 30, 151, 189 ] I couldn't find any parameter in the API docs that does this, so I was thinking of creating a custom plugin to maybe filter and substitute the tag ID's for names before the response is sent back to the API caller. In that case, what action should I listen for?
I figured something out based on what I found at this post. Basically I need a plugin that listens for when the REST response is about to go out. The plugin code would be similar to the following: function ag_filter_post_json($response, $post, $context) { $tags = wp_get_post_tags($post->ID); $response->data['tag_names'] = []; foreach ($tags as $tag) { $response->data['tag_names'][] = $tag->name; } return $response; } add_filter( 'rest_prepare_post', 'ag_filter_post_json', 10, 3 ); It adds the tag names as a new property called `tag_names`. The rest of the heavy lifting is done by the `wp_get_post_tags` function.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 3, "tags": "tags, api" }
Should I install plugins to my WordPress installation from web sites having in URL "nulled" or, "null"? I would like to bring some attention to WordPress people. On few places or Websites you may find some plugins for free that usually cost money. These websites usually have "null" or "nulled" in URL. Should I install them?
No. This is a security risk. Not only morality question. I checked some of these plugins and found most of all of these are infected. For instance, they will use `base64encode` functions and evaluate in the end to send info from your web site to URLs in Panama, Iran or like. They may write to your `license.txt` or `readme.txt` files for instance, and in that way the hackers can get your credentials. **Note** There may be honest businesses having "null" or "nulled" in URL so I would like to enclose, since I meant specifically those web sites delivering hacked plugins.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, security, plugin recommendation" }
Strange characters added to the database So I am migrating over a Wordpress website it has quite a lot of custom fields, long titles and a lot of images. When I make the migration over the database is not seen and Wordpress goes to a fresh install page, then it makes up a new database. In PhpMyAdmin I can see the old database is still there and it uses normal conventions like wp_commentmeta but the new version (the one WP has no problem seeing but no info from the old site) puts in odd characters like wp_z5v95e_commentmeta? Even if I kill the database, rename it, re-du the con-fig file, get rid of the plugins, get rid of the theme, do a fresh WP install and I still get wp_z5v95e! If I have to start from scratch and rebuild the site so be it but it also doesn't see the media library which is key due to the amount of images in the website. Has anyone seen or know what this is? Thanks
The strange characters you are referring to are part of the table prefix. This is configured with the variable `$table_prefix` in the file wp-config.php. $table_prefix = 'wp_'; When migrating a WordPress installation and setting up a new wp-config.php file you have to make sure, the prefix stays exactly the same as in the former config file. Else all database tables have to be renamed accordingly.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "database, migration" }
Password Protected Logout Button Not Working Hello Wordpress StackExchange, I have a question regarding what I could do using the following, please review the link below which fully explains my scenario and give me some input to what I could try to remedy my Password Protected Logout Button issue? < Thanks for your support, LVFIT
This may be marked as resolved since Studiopress Forum Support has given the needed direction on their site directly.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "password" }
How to get this only in small letters (lowercase)? I used the following code to give out the category name (without link) in a single post. How would it be possible for the category name that is given out to only appears in small letters ? I just think this has to be made with substring, but I dont get it :) Could somebody please help me :) <?php foreach((get_the_category()) as $category) { echo $category->cat_name . ' '; } ?>
I would personally achieve this by using `strtolower` which changes the case of the string. <?php $categories = get_the_category(); foreach($categories as $category) { echo strtolower($category->cat_name) . ' '; } ?>
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "categories" }
Open graph 'image' content appears empty on debugger and filled in web source Defining Open Graph meta tags like this for images. global $post; $postImg = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 1200, 9999 ), false ); <meta property="og:image" content="<?php echo $postImg[0]; ?>"/> <meta property="og:image:width" content="<?php echo $postImg[1]; ?>"/> <meta property="og:image:height" content="<?php echo $postImg[2]; ?>"/> I get this in my website source: <meta property="og:image" content=" <meta property="og:image:width" content="2953"/> <meta property="og:image:height" content="4134"/> But this in facebook's Open Graph debugger (what scrapper sees). <meta property="og:image" content=""> <meta property="og:image:width" content=""> <meta property="og:image:height" content=""> Thank You
The problem was using scheduled pots with $post->post_status => 'future'. Scheduled posts can be tricky to handle. So, the solution is to trick them into being $post->post_status => 'publish' when saved, as shown in this answer: Marking future dated post as published
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "tags, open graph" }
Do action only on certain front end pages? I am creating a plugin that allows users to insert certain code on their specified page or post of their choice. I have tried doing this: function asdf() { $siteURL = get_site_url() . '/'; $pages = get_pages(); foreach ($pages as $page ) { $pageTitle = get_page_link( $page->ID ); if ( $siteURL === $pageTitle ) { echo "this is the correct page" . "<br>"; } else { echo "this is the wrong page". "<br>"; } } } add_action('wp_head', 'asdf'); If you run this code, you will see that it treats all pages the same, and there would be no distinction in the results across different pages. However I am trying to get my function to treat each page uniquely, and give different results based on each page title. Thanks in advance.
to test if you are on specific page, you just need to test the identifier like that : add_action("wp_head", function () { $idPageToTest = 32867; if ( isset($GLOBALS["post"]) && ($GLOBALS["post"]->ID === $idPageToTest) ) { echo "We are on page $idPageToTest."; } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, plugin development, pages" }
'Screen Options' is missing. Where should I start troubleshooting? My plugins are updated, my WordPress core is upgraded, and I don't have anything too fancy on the website. Yet 'Screen Options' is missing. Where should I begin troubleshooting?
See if there are errors in the developer console (F12 on most browsers) If not, disable all plugins. If screen options return, enable the plugins one-by-one to see the offender. If that doesn't help, switch to the default theme to see if that's the issue.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "screen options" }
Is there a get_post(s) filter that can alter/replace the output completely? I would like to create a plugin that creates a JSON cache of saved/updated data. But for the plugin to be general purpose I'd need it to override the output of `get_posts` and other `get_functions`. I know that html cache is faster and that good plugins already exist for that purpose, but this would be a nice thing to have when building a SPA, and in scenarios where table locking occurs like in Woo Commerce sites. There are hooks like `updated_post_meta` and `post_updated` but I couldn't find the `get_posts filter`. There is `pre_get_posts` but it only allows for the `$args` modification, the underlying `WP_Query` is still ran.
If you look towards the end of the query process (which starts with the `pre_get_posts` filter), there is a filter called `the_posts` (not to be confused with `the_post`). This allows you to modify the output of `get_posts` completely, as you asked. Beware that this only works if there is no plugin or so that suppresses filters on `get_posts`. Also note that this doesn't work on `get_post`.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "filters, get posts, cache, json" }
WP Title only in lowercase letters how to get `<?php wp_title(''); ?>` only in lowercase letters ? I tried a lot but cant get it ! Perhaps one of you can tell me how to proceed ?
You can use string to lowercase php function, that'll help you out.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -4, "tags": "wp title" }
Getting rid of unused css directives I bought a theme (developed on top of another theme as I discovered later), modified it deeply as a child theme and now I have thousands (more or less 15000) of css lines unused. Is there an efficient way of deleting what I don't need. By efficient I mean not one by one. Do you I earn something in terms on performance?
The guys behind this project I trust a lot. < Also I used this long time ago: < However, you need to be careful, because you must not remove some CSS that will be used in the future, or in case some feature is enabled later.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, css, child theme" }
changing static link to relative link I have self hosted my wordpress today, but I realised it is still having static link of my local installation, since now I am opening using my IP (as i haven't done DDNS yet) i want that link should change to IP followed by ret of the URL instead of static local url. Any help would be greatly appreciated.
If I'm understanding your question correctly, you want links on your site to dynamically change depending on the domain name of the environment you're in? To do this you can replace any hard coded links with the `home_url()` function. So you would change references to links from ` to `<?php home_url(/your/path/here); ?>` If your links were defined through the Wordpress Admin UI then you'll need to use filters or change all the links via an option in Settings. Refer to this question for details: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, urls, links" }
Remove url rewrites for registered taxonomies According to this having many url rewrites doesn't slow down website. But neverthless is it possible to disable generating those rewrites when I register taxonomies? Becase only for this one CTP I have 60 unnecessary rewrites. // Register CTP $args = array(...) register_post_type('my_ctp', $args); // Register 12 months as taxonomy for CTP (each of them have a few custom terms inside) foreach($this->months as $month => $month_var) { $args = array( 'labels' => array('name' => $month), 'hierarchical' => true, 'sort' => true, /* 'public' => false, 'show_ui' => false, 'show_in_nav_menus' => false, 'query_var' => false*/ ); register_taxonomy($month_var, 'my_ctp', $args); } This is example of a rewrite for one custom taxonomy ![enter image description here](
in the args try to add this : "rewrite" => FALSE,
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, custom taxonomy, url rewriting, rewrite rules, register taxonomy" }
How can I display a query in a page? I'm new with Wordpress development and I trying to display a query result from the wp_postmeta table. Does anyone know how to that? Do I have to connect with the MySQL with `mysql_connect()` or does WP have a built-in function for that? Thanks!
You can use the `$wpdb` object // Print last SQL query string $wpdb->last_query or: <?php if (current_user_can('administrator')){ global $wpdb; echo "<pre>"; print_r($wpdb->queries); echo "</pre>"; }//Lists all the queries executed on your page ?> You might have to set `define('SAVEQUERIES', true);` in `wp-config.php`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, wp query, functions, query, mysql" }