INSTRUCTION
stringlengths 11
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
WooCommerce - Hook after Loading Variation in Admin Edit page?
In Product's Edit page, when we click Variations, we will see AJAX loading for all of its variations.
Is there a Hook for when it finished?
I want to run a script to add some "at-a-glance" information on each Toggle Header. For example "Sold Out" label when the variation has 0 stock.
Thanks | In `woocommerce/includes/class-wc-ajax.php` there is a method on the `WC_AJAX` class responsible for loading variations called `load_variations`, it contains only one hook, which is a filter, named `woocommerce_ajax_admin_get_variations_args` which fires early in the method.
However if you are looking for something client side, then `woocommerce/assets/js/admin/meta-boxes-product-variation.js` triggers an event on the success callback of the `load_variations` function named `woocommerce_variations_loaded`.
Therefore if you are looking to fire subsequent actions using JS, then:
$(document).on('woocommerce_variations_loaded', function(event) {
//your code here...
});
Or you can try binding to the element in which the trigger is executed upon:
$('#woocommerce-product-data').on('woocommerce_variations_loaded', function(event) {
//your code here...
}); | stackexchange-wordpress | {
"answer_score": 10,
"question_score": 3,
"tags": "woocommerce offtopic"
} |
SQL command to convert all tags in lowercase?
I'm looking for a SQL query command to convert every single tag in every post ever used to be converted into lowercase. | Try this SQL query:
UPDATE wp_terms SET name=LOWER(name); | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "mysql, sql"
} |
Woocommerce 404 after chang default language
After change default language in Woocommerce from Dutch to English I get 404 errors. I also have installed latest version of WPML. 3 Languages are active: EN - NL - DE. When I edit a link to open an category the link is as follow:
myshop.com/en/category/end-user/absorbin/ // result not ok
myshop.com/nl/category/end-user/absorbin/ // result ok
this results in a 404 error
when deleting /en/ string for default lang = EN the link works fine.
myshop.com/category/end-user/absorbin/ // result ok
Is there a possibility to prevent these 404 errors, instead of changing manually all the links in pages and so on? Maybe a rewrite rule in .htaccess
But I have no experience with that. | Found the necessary setup in WPML:
[<
Problem solved. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -1,
"tags": "woocommerce offtopic, htaccess, 404 error"
} |
srcset and custom field get_post_meta and wp_get_attachment_url
I would like to use the new wordpress 4.4 function srcset with an image which comes from a custom-field like this
<img src="<?php $bigimg = get_post_meta($post->ID, 'bg_file', true); echo wp_get_attachment_url( $bigimg );?>" alt="">
How could I get the srcset function work with it?
wp_get_attachment_image_srcset( 380, 'medium' );
srcset is already activated for post_thumbnails in my functions.php.
Thank you! | Just put two and two together:
<img src="<?php $bigimg = get_post_meta( $post->ID, 'bg_file', true ); echo wp_get_attachment_url( $bigimg ); ?>" srcset="<?php echo wp_get_attachment_image_srcset( $bgimg, 'medium' ) ?>" alt="" /> | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "functions, images, responsive"
} |
Can you navigate away from the updates screen during an update?
Bit of a _random_ question, I was running an update on a plugin, and went to `⌘` \+ **click** another item from the the dashboard menu, finger slipped and I ended up going straight to that page before the updates had finished.
I immediately went to the updates screen and the update had _gone_. I checked for updates just in case, but nothing. After looking in plugin changelog I can confirm it did update.
So my question is, do you have to sit through the update screen? Or is it enough to just "start the process" and you can click away to other pages on the dashboard. | Yes, server do not need any user input to complete the update, and once the request was received by the server it do not terminate it even if the connection to the browser had died (this is why it is actually impossible to cancel operations once started). Still it is probably better to leave it open to make sure the update was successful. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "dashboard, updates"
} |
Wordpress subfolder installation AJAX Problem
I installed a Wordpress distribution in a subfolder. Everything works fine: The rewrite rules a correct and so on.
only my own private plug-in doesn't. I call per ajax the plug-in function via the url: /wp-content/plugins/plug-in-name/save_contribution.php
The absolute path is: <
I know that's not the proper way to do AJAX in WP but I can't change it right now. I will in future - I promise :-)
The interesting point is: When I call it, it loads: <
So it goes back to the root. And it finds it because I have a different distribution in my root with the same plugin - so it writes in the wrong database
Can someone help me one that?
And again, I will rewrite my plugin in future but now I have to solve that issue quite quick!
Thanks | Use `plugin_dir_url` to get the URL of your plugin's directory.
$ajax_url = plugin_dir_url( __FILE__ ) . 'save_contribution.php' | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, ajax"
} |
WordPress Dashboard Problem
I am having difficulties changing my dashboard address. Currently it is pointed to my_domaincom.wordpress.com/wp-admin while it needs to be my_domain.com/wp-admin: with the current dashboard I cannot upload themes (see images below).
There is no "Add New" button.  that has the 'Add New' button. . My problem is that the right edge of the videos (such as where the full-screen button would show) are being cut off by my blog's sidebar. I've tried looking through my theme's options and WP settings for a way to keep the videos sized properly so they don't conflict with the taskbar - but I can't find any such options.
I'm starting to reluctantly think I may have to dig into some CSS to fix this, but I'm not sure how to find the right file(s) or exactly what I'll need to add / edit. Any help would be appreciated. | _I remember when TED videos firstbrought me here to WPSE some time ago :-)_
The global _content width_ or the _embed size width_ option `embed_size_w` might be slightly off on your site.
Alternatively you could manually insert the _width_ :
[ted id="2252" width="600"]
where the _height_ is then adjusted to give you the `16x9` aspect ratio.
Note that TED oEmbed support was added into WordPress 4.0 | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "embed, videos"
} |
What is the impact if i ignore title and content in my custom post types CPT?
I am using CPTs (with PODS) and i need to "ignore" in "supports" the title and content.
I have no problem to alter the columns in the admin manage CPT list.
Also i understand that the standard functionality of WP that manages the content and title will not be there and i will have to manage my meta info in the various templates.
Other than that do i have any problem if i ignore them and leave them blank? | If you supply no title, WordPress will set the title to: (example)
## (no title)
This will be shown in the list table for the post type in the admin area, within the database, the `post_title` value will be empty.

## 1234
...where 1234 is the ID of the object. The `post_name` value in the database will receive the ID.
 for the `post_content` field, then your post will be set to `auto-draft` for the `post_status` column.
So you might need to use the `save_post` hook to set a default value for the `post_content` field. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 2,
"tags": "custom post types, title, content"
} |
Load front-page.php from subfolder
My `front-page.php` works fine in the WordPress root folder. But I would like to put it in the _page-templates_ subfolder.
How do I make it load from there? | You can make use of the `frontpage_template` filter to adjust where your template should be loaded from
add_filter( 'frontpage_template', function ( $template )
{
$locate_template = locate_template( 'page-templates/front-page.php' );
if ( !$locate_template )
return $template;
return $locate_template;
}); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "frontpage, template hierarchy"
} |
Do I need the .po file for my plugin?
I've a couple of language files in my plugin. Each language has a pair of files with extension `.mo` and `.po`.
domain-de_DE.po
domain-de_DE.mo
When I remove the `.po` files the translation still works so I'm thinking about getting rid of the `.po`'s and keep the `.mo`'s.
Is this a problem or what's the idea of having both for each language? | keep the .po. If someone will want to modify your translation he can do it based on your .po but it is much harder to do it (if possible at all) based on the .mo file.
You don't save much by not distributing the .po and it keeps things organized for you as well. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "localization"
} |
Get posts by language in Polylang plugin
I use the Polylang plugin to translate my website in Italian and German. How can I get the latest post in Italian?
I'm using the arguments below to get the content of the post, which afterwards I send via newsletter, but I don't know how to get the right language.
$args_menu = array (
'post_type' => 'EXAMPLE',
'order'=> 'DESC',
'paged' => $paged,
'post_status' => 'publish',
'posts_per_page' => 1,
'suppress_filters' => false
); | If you use the query_post function, I think you can just add the 'lang' parameter:
$args_menu = array (
...
'lang' => 'it',
...
);
See : < | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "get posts, plugin polylang"
} |
How to create an incremental list using shortcodes?
Right now I'm creating shortcodes like this:
function short_code($atts) {
$a = shortcode_atts( array(
'name' => ''
), $atts );
return '<div class="content">
<div class="container">
<p>' . esc_attr($a['name']) . '</p>
</div>
</div>';
}
add_shortcode( 'short-code', 'short_code' );
// Usage: [short-code name="John"]
How to do it so I can have incremental shortcodes? In other words, to modify the shortcode so I can do this? `[short-code name="John" name="Jack" name="Mary"]` and produce something like this?
<div class="content">
<div class="container">
<p>John</p>
<p>Jack</p>
<p>Mary</p>
</div>
</div>
I searched on Google but I couldn't find anything. | What you want is to use shortcode attributes. I Googled "wordpress shortcode attributes" and found the sample code below in the WP Codex
// [bartag foo="foo-value"]
function bartag_func( $atts ) {
$a = shortcode_atts( array(
'foo' => 'something',
'bar' => 'something else',
), $atts );
return "foo = {$a['foo']}";
}
add_shortcode( 'bartag', 'bartag_func' );
You would want to pass an array for the example you show in your question
[short-code names="John", "Jack", "Mary"]
You can get the list of names by following the sample code and accessing the names array:
foreach($a['names'] as $name){
echo "<p>$name</p>";
}
Edit: Just to be clear you would get the array from args as such:
$a = shortcode_atts( array(
'names' => 'names'
), $atts ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "shortcode"
} |
Do I need to prepare query before get_results(), get_row() and get_var()?
I know that we don't need to use prepare($query) when we put it in insert() and update() because these functions sanitize data for us but I'm not sure if we need to prepare query before putting it in get_results(), get_row() and get_var()?
Thank you. | If your query has no dynamic input, then you technically do not need to use `$wpdb->prepare()`, however that assumes your own input is safe.
If your query contains parameters in which are dynamic, especially supplied by users from a form as an example, then you will want to use `$wpdb->prepare()`.
Using `$wpdb->prepare()` is just good practice, but in order to use it, you must pass at least two arguments (the query, and at least one placeholder).
> Please note: As of 3.5, wpdb::prepare() enforces a minimum of 2 arguments.
See: < | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "php, mysql"
} |
Cannot find the code for "Edit This" link in posts in a specific theme
I cannot for the life of me find the code for this particular item:
, 'post-formats' ) ? get_post_format() : get_post_type() ) );`
I have no idea how to go from there. I don't get the Theme code structure at all.. | This should be located in the `entry-meta.php` file of the parent theme (kuorinka). Here is the code:
<?php if ( 'post' == get_post_type() ) : ?>
<div class="entry-meta">
<!-- Date & Author name-->
<?php kuorinka_posted_on(); ?>
<!-- Comments count -->
<?php if ( ! post_password_required() && ( comments_open() || '0' != get_comments_number() ) ) : ?>
<span class="comments-link"><?php comments_popup_link( false, false, false, 'comments-link', false ); ?></span>
<?php endif; ?>
</div><!-- .entry-meta -->
<?php endif;
The function `kuorinka_posted_on()` is defined again in the parent theme in `kuorinka\inc\template-tags.php` on lines 36-58. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "themes, theme options, code"
} |
Media items hogging pretty permalinks
I have a WordPress installation setup but I'm having trouble with items uploaded to the media library taking up pretty permalinks. The only way to fix it that I've figured out so far is to delete the image from the library. However the image in question is used all over the site so I would much rather find another solution.
**Example:**
Say I upload an image called `foo.jpg` then make a page called `foo`, the pretty permalink for the page becomes `/foo-3`. If you try and change it, it reverts back to 3, unless you use something that isn't 'taken'. If I navigate to `url.com/foo` I get the attachment page for the image and not the page.
I've tried changing the permalink settings to all the different settings. I've also tried renaming the image 'title' but that is no good either.
Is there anything else I can do to force the permalink?
Thanks | It's not your permalink settings, it's the fact that `foo.jpg` was uploaded first and "stole" the slug `foo` \- you need to change it to something else, _then_ set your page slug.
Go to Media > `foo.jpg` > Edit (if you are in grid view, you need to go to "Edit more details")
 and set it something that isn't `foo`.
Now go re-save your page with slug `foo`. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "permalinks, uploads, media, media library"
} |
Modify custom field input data before creating a new post
I'm try to check input data before it is added to DB. For example:
I have a custom post meta named `book_isbn` in post page. I want to make sure that this variable `$_POST['book_isbn']` is valid before it is added to DB.
So far I know that I can use hook `wp_insert_post_data` to achieve this. I'm not sure if I did this right. It doesn't work for me. Please check the code below.
add_filter( 'wp_insert_post_data', 'clean_data_before_post_created', '99', 2 );
function clean_data_before_ad_created( $data , $postarr ) {
$data['book_isbn'] = clean_isbn($_POST['book_isbn']);
return $data;
}
Thank you. | This runs your function right after the post has been saved (created/updated):
add_action('save_post','clean_data_while_saving_post',1);
function clean_data_while_saving_post($post_id) {
$data = get_post_meta($post_id,'book_isbn',true);
update_post_meta($post_id,'book_isbn',clean_isbn($data));
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "php, functions, customization, hooks, actions"
} |
Display list of custom post type which match taxonomy
I'm trying to add a snippet in my Wordpress sidebar which displays a list of links to posts which match a criteria.
I'm using a Custom Post Type **cars** and a taxonomy **car-types** and I'd like to display a list of links to **cars** which are part of the **car-types** taxonomy.
So in short. Display list of links where post is a custom post type called **cars** and the **car-types** taxonomy is **SUV**
Is there a way of doing this please? | Hopefully this will help out.
<
<?php
$args = array
(
'post_type' => 'cars',
'tax_query' => array
(
array
(
'taxonomy' => 'car-types',
'field' => 'slug', //or name or term_id
'terms' => 'suv',
)
)
);
$car_query = new WP_Query($args);?>
<?php if($car_query->have_posts()):?>
<ul>
<?php while($car_query->have_posts()): $car_query->the_post();?>
<li>
<a href="<?php the_permalink();?>"><?php the_title();?></a>
</li>
<?php endwhile; wp_reset_postdata(); ?>
</ul>
<?php endif;?> | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types"
} |
Wordpress Schema.org Markup. What value does it add?
I've been adding all the _"recommended"_ **schema.org** markup to my sites for awhile now. Most of the schema markup adds value to google searches.
There's other markup though that I've been using and I'm not really sure who actually uses it (search engines, other sites, etc).
**Specifically, for this question, I'm wondering about the wordpress related schema.org markup:**
**Header:** `<header itemscope itemtype="
**Sidebar:** `<aside itemscope itemtype="
**Footer:** `<footer itemscope itemtype="
Does anyone know what the purpose of this markup is? Does it add SEO value? If so how and where? Thanks! | The `WP` in their URLs is not related to WordPress, it’s just a shorthand for **_W** eb **P** age_. These types all have the type `WebPageElement` as parent.
In my opinion, using `WebPageElement` or one of its sub-types (like `WPHeader` etc.) is pointless for general web pages (there are some special cases and non-HTML contexts where it might make sense to use these types). It can even be hindering to have these types, because it’s not (easily) possible to provide content in `WPHeader`/`WPFooter`/`WPSideBar` as value for a property that should belong to the parent `WebPage` item (e.g., if your `WPFooter` contains a license statement, the `license` property would specify the license for the `WPFooter`, not for the `WebPage`).
Neither Google Search (doc.) nor Bing (doc.) nor Yandex (doc.) document any feature that would make use of these types. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "templates, google search, search engines, html"
} |
Make wordpress pages accessible for Woocommerce logged in users only
I have created one page on my WordPress that I want to set only woocommerce user can view it. That mean they must logged in first to be able to view it. For unregistered user if they try to access to that page, we will redirect them to my-account page.
I found this similar solution but this only work for woocommerce pages but how to insert to code for wordpress pages. This is the code:
function wpse_131562_redirect() {
if (
! is_user_logged_in()
&& (is_woocommerce() || is_cart() || is_checkout())
) {
// feel free to customize the following line to suit your needs
wp_redirect(site_url('my-account/'));
exit;
}
}
add_action('template_redirect', 'wpse_131562_redirect');
Let say my page is `mydomainname.com/wordpress-pages`
How to be able to restrict that pages? looking forward your help. | Add your page slug in if condition too.
function wpse_131562_redirect() {
if (! is_user_logged_in()
&& (is_woocommerce() || is_cart() || is_checkout() || is_page('wordpress-pages'))
) {
// feel free to customize the following line to suit your needs
wp_redirect(site_url('my-account/'));
exit;
}
}
add_action('template_redirect', 'wpse_131562_redirect'); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "pages, woocommerce offtopic, login"
} |
Proper way to hook wp_get_attachment_url or any other way to change that url in media library
I am trying to hook wp_get_attachment_url() with my custom implementation. I am trying to get my post videos and any other static data from the Amazon S3 and I was wondering if I can configure the URL with my Amazon bucket URL.
This is what I was trying to do
add_filter('wp_get_attachment_url', 'custom_get_attachment_url', 1, 1);
function clrs_get_attachment_url($post_id = 0) {
// change URL for Amazon bucket
}
but this is not working as expected as I am getting $post_id as 0. How to do it in a proper way? | The filter has _2_ parameters, also the function name doesn't match. So your code should look like this:
add_filter('wp_get_attachment_url', 'clrs_get_attachment_url', 10, 2);
function clrs_get_attachment_url($url, $post_id) {
// Do what you want to $url
return $url;
} | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 4,
"tags": "media library"
} |
can't see aditional themes in control panel
I installed wp 4.2.2 on xampp localhost - multisite, following this article <
xampp is surely ok, because it works a year without a problem.
The new installation is wordpress only.
Installation seems ok, but starting dashboard - Appearance - Themes I can see just current theme (Twenty Sixteen), without any button to load additional themes.
I checked wp-content folder - there are three default themes there.
Any help? | Could be a few things causing it. Have you altered any core files or wp-config in anyway?
Are the themes definitely valid, they have a style.css file with the required information filled in?
I'd recommend setting up a completely fresh WordPress installation. Copy each theme in one at a time and make sure they show up.
If they do, it's most likely something wrong with your core setup/wp-config file. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "themes, localhost, xampp"
} |
Passing User Messages to Another Page
I've got a form that does a fair bit of processing. Along the way, things may not work out as expected, and I want to display messages to the user. I've got that working.
However, if things go well, I also want to let the user know. But here's where it gets dicey: I want to go to the custom login page (via wp_redirect()) and display the message there. So, how do I send the message to the login page?
I've dreamed up a pretty involved mechanism, that may work. But I figure this is a fairly standard pattern: WP must already have something in place for this sort of thing. | A standard approach is to add a query parameter to the location header (redirect), for example:
$redirect = add_query_arg( 'my-form', 'success', $redirect );
wp_redirect( $redirect );
exit;
Then on the redirected-to page, you can conditionally display a message:
<?php if ( filter_input( INPUT_GET, 'my-form' ) === 'success' ) : ?>
Congrats!
<?php endif ?> | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 2,
"tags": "wp redirect"
} |
How to remove Date from Meta Description on SERP?
I noticed on a few recent projects the Date is displaying in the Meta Description for all Custom Post Types and Taxonomies in WordPress. I was always under the impression the Date would usually show for 'Posts', which has always made sense. Then for Pages and Taxonomies - which would normally be evergreen content in most scenarios NO date would appear when seeing the snippet on a SERP.
I use the Genesis Framework and Yoast SEO for most projects and have looked into seeing if the date showing in the meta description is related to the Parent Theme or Plugin and it doesn't seem to be.
Yoast say the date is produced naturally by Wordpress.
I'm slightly confused though as I have never had this issue until recently, I was interested in seeing if anyone else has noticed this and if there is a solution to removing the date from all CPTs and Taxonomies? | If anyone else encounters this, check your source code and try and find the date in question to see where it's being inputted, Googlebot normally finds these dates there.
It turned out the Googlebot was picking up a date in the footer of my site, via the WordPress Latest Posts Widget, where I had selected the option to feature the Post date. Resulting in this date showing in the source code of every page throughout the site. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "post meta, date, seo, genesis theme framework, plugin wp seo yoast"
} |
Control whether or not to trash a custom post type
I need to have control over the trash / delete action on a custom post type.
I need to check for some conditions and decide if i should trash the CPT or not.
The wp_trash_action hook that is fired before the trash function does not give me the option to cancel the trash procedure.
To be more specific , i need to check for a condition when the user presses TRASH. If that condition is false then i need to stop the trashing action. If it is true it should continue. | Hook onto `trashed_post` and use `wp_untrash_post()` to reverse upon meeting a condition, pseudocode example...
add_action('trashed_post', 'wpse_218031_trashed_post');
function wpse_218031_trashed_post($post_id){
//use post_id to check conditions... if not met call:
if ( $some_condition ) {
wp_untrash_post($post_id);
}
}
`trashed_post` runs after `wp_trash_post` and after the post is moved to trash.
By the way, if the constant `EMPTY_TRASH_DAYS` is defined and is `false` posts will be permanently deleted and the subsequent hooks mentioned will not be fired, in which case `wp_delete_post()` will be called instead. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 1,
"tags": "trash"
} |
How to set a header in wp_safe_remote_get()?
Previously I am using the below code. Now I need to change this code and replace `file_get_contents()` with `wp_safe_remote_get()`. I need to know how to set `'header' => "Accept: application/json"` in `wp_safe_remote_get()`:
$opts = array(
'http' => array(
'method' => "GET",
'header' => "Content-Type:application/json",
'header' => "Accept: application/json"
)
);
$context = stream_context_create($opts);
$file = file_get_contents(
'
false,
$context
);
I have tried to do this but not working
$args = array( 'timeout' => 30 , 'header' => "Accept: application/json");
$file = wp_safe_remote_get(' $args); | This will work
$args = array( 'headers' => array("Accept" => "application/json"));
$file = wp_safe_remote_get(' $args);
headers is an array. Not a string . | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugin development, http api"
} |
Developing a plugin where users can edit entries saved in database
it's the first time I'm writing a plugin. So far, it creates a table in database on activation, users can add entries to database and they can check saved entries.
I've added Edit and Delete links where I pass the id, but I don't want to edit entries on a different page. How to do it so it's on the same "environment"? Make it something like Users in WordPress, that kind of functionality? | I've managed to do it, but probably there is a much cleaner WP way of doing these things.
So, I have a menu page that I've added using add_menu_page. On it, I display all the records. The url is:
/wp-admin/admin.php?page=plugin-settings (or whatever you call it)
I use:
<a href="<?php echo bloginfo('url');?>/wp-admin/admin.php?page=utm-user-plugin-settings&id=<?php echo $row->id; ?>">Edit</a>
So basically, I ended up using the same page for my EDIT action by checking if $_GET["id"] is set or not.
Again, there is probably a better way to do this, I just don't know it yet, so this will do for now. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "plugin development, admin menu"
} |
issue in wordpress auto delete post and redirect to another 1
i am getting strange issue on WordPress, my site is huge traffic and database. one thing.. my WordPress is updated 4.4.2 all plugins updated. now i get issue when i publish new post most of the posts deleted first time. after publish i check view post it works fine and vie. and then after 1 minute post deleted and not showing in all posts section in admin, if i manual open link then it redirect to another post. i checked no redirection set to any of these post. i used 301 redirect plugin if i need set redirect, please help me to solve this issue. | OK i get solution from senior developer and tested.. problem is too many revisions and auto draft that's why WordPress confuses to save new posts.. it works. i just install a plugin `WP-optimize` and click proceed it delete all posts which has status revision and auto draft.
regards, ahsan | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "posts, admin, wp admin, redirect, customization"
} |
single-{post-type}.php
I have implemented a custom post-type "project". To see the page of the archives of these custom post types, I created an archive-projet.php To see this page, I type < so far no problems ..... Where it gets complicated is when I want to see the single-projet.php page.
When I click on the link in the project archive-projet.php page, a blank page is displayed! I do not understand ! Someone would have any idea ? Thank you for your lights. | Based on the amount of times you missed the c from the word project... my first recommendation would be to check for typos in your code/file names :)
Try updating permalinks in here: /wp-admin/options-permalink.php. Just hit update, and see if that solves the problem.
Also, see if any errors are getting reported, open up wp-config and change `define('WP_DEBUG', false);` to `true`. Then try your single page again and see if any errors come back.
You could also check your PHP error logs for any signs. | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "custom post types"
} |
Create Admin Only Taxonomies?
Is there a way to create admin-only taxonomies in wordpress?
I have some things I'd like to tag with private, admin-only terms (for various reasons.) Is there a way to do this?
**EDIT** : Use case: I don't want the taxonomy or their terms getting their own url. i.e site.com/taxonomy/term
I also don't want the terms searchable on the frontend | I believe when registering the taxonomy: setting `public` to false and `show_in_menu`, `show_in_nav_menus`, `show_ui` all to true would solve what I _THINK_ is your request, without knowing any further what your use case is. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "custom taxonomy, wp admin"
} |
variable endpoints for webservice
New to wordpress development, I am working on a plugin that retrieves data from a webservice.
I need an endpoint because the retrieved data also depends on the value of the page's metabox, so in effect the post endpoint variable url is to display a virtual child page.
The desired url would look like this:
**example.com/department-a/individuals/smith.john**
I need the /(page)/ with /(endpoint)/ and /(variable)
The examples I've seen so far, all point to the use of specifically defined variables after the endpoint. Is it possible to have an endpoint with a query variable after? | Ok, so it might have been working all along, and I just hadn't flushed the rewrites!
function my_dept_listing_init() {
//Easy flush
if (isset($_GET['flush'])) {
flush_rewrite_rules();
}
//endpoint onto which queries are made
add_rewrite_endpoint( 'individuals', EP_PAGES );
//This filter acts as a controller, inject into content
add_filter('the_content', 'my_dept_listing_content_ctrl');
}
add_action('init', 'my_dept_listing_init');
function my_dept_listing_content_ctrl($content) {
global $post;
$getName = get_query_var('individuals');
$post->post_title = $getName;
//Etc
}
Hope this helps someone! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "url rewriting, endpoints, web services"
} |
Does wp_query and query_posts affect website performance?
I've been aware about the difference of wp_query and query_posts. I just want to know what impact does both query methods to the performance of the page? Which query method makes the page load quicker or slower? | The question was answered a few times on this site. Have a look at this answer | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "php, wp query, query, query posts"
} |
How to insert variable which contain array value in wp_options table?
I have create a form and i want to store the form data in `wp_options` table so for that i have created this query
$insertquery = $wpdb->query("INSERT INTO `wp_options`(`option_name`,`option_value`) VALUES ('smsfactory123','asdasdf')");
Now when i am importing the static data then it doesn't create any problem when i pass the variable which is containing array it shows me error.
$apidetail = array(
'userid' => $uid,
'userpassword' => $upwd,
'senderid' => $sid,
'ono' => $ono,
'message' => $message,
);
This is how i am getting value of array in variable | You could also use `json_encode()` function instead of `serialize`.
$var = json_encode($array);
update_option('option_name', $var); | stackexchange-wordpress | {
"answer_score": -1,
"question_score": 0,
"tags": "plugins, plugin development, wp query"
} |
Wordpress has a trash for users? (Wrong result for count_user, greater than expected)
I am using count_users() function to count users on my wordpress sites. In my administration area -> 'Users' I can see 7 users, but the function returns 9. After some time, searching for errors in my code, I noticed that in the admin area there are 7 users listed, but near the 'All' link there is a number counting users and the number is effectively 9.
So, what is happening? Maybe there is a trash for users, and Wordpress is still counting deleted user or something like that?
EDIT: Just for the sake of completeness, tried to delete an user and the total counter is correctly lowered by one unity. Still having two phantom users... | No, the user system does not have a trash (this is the default, obviously you can add pretty anything).
My problem was caused by users meta... If you take a look at the the function count_users (located in wp-includes/user.php), you'll see some comments there. It says that the function:
* Assumes there are neither duplicated nor orphaned capabilities meta_values.
* Assumes role names are unique phrases.
In my case, there were orphan meta values. Deleting from wp_usermeta values having a user_id not present in wp_users table solved the problem.
Delete can be performed with a mysql query like this
DELETE FROM wp_usermeta
WHERE NOT EXISTS (
SELECT * FROM wp_users
WHERE wp_usermeta.user_id = wp_users.ID
) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "users, trash"
} |
Where to put API Code?
I want to use some of the Wordpress API built in functions such as wp_remote_request(). I have tried using this in a php file in my root Wordpress installation but I am just getting an error:
> Fatal error: Call to undefined function wp_remote_request() in /home/pacekuwa/public_html/gf.php on line 23
I have a feeling I am not putting my code in the right place or need to include one or more Wordpress files...
Could anyone tell me where I should be putting my code?
EDIT:
I am trying to create a page that makes a remote API call to my Gravity Forms plugin to retrieve submitted form entries using the Gravity Forms Web API. I was trying to follow their example, but don't know where the code they give should go within my installation to get it to work. | You can create a plugin to contain your code. The `admin_post_` action) can be used to trigger a request handler. WordPress core will be loaded, and the API will work.
<?php
/*
Plugin Name: Ben's GF Plugin
*/
// for logged-in users
add_action( 'admin_post_ben_gf', 'ben_gf_handle_request' );
// for non logged-in users
add_action( 'admin_post_nopriv_ben_gf', 'ben_gf_handle_request' );
function ben_gf_handle_request() {
// Your processing code.
// WordPress functions will work here.
echo 'Your home url: ' . home_url();
// die() at the end to terminate execution
die();
}
This will map your request handler to the URL:
Use caution if you are allowing non-logged in users to access this URL, you don't want to publicly expose sensitive data. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "api"
} |
Do tags have dates?
I've created something using reverse tags – when something isn't tagged, it's flagged up to say "Hey! This post hasn't been checked yet!"
Now i'm wondering, is there a way to get the last tag created?
Do tags have modified / created dates? Is there a way of getting around this if they haven't?
The user case I have is security patches for a CMS and I have a team who are documenting everything about it. I want them to create a new tag for the patch, then have a notice display saying "New patch available"
Anyone crossed anything like this before? | Following @PieterGoosen's (credit due) train of thought hook onto the following:
function update_term_timestamps($term_id) {
switch( current_filter() ) {
case 'created_term':
update_term_meta($term_id, '_term_created_at', current_time('mysql', true));
break;
case 'edited_term':
update_term_meta($term_id, '_term_edited_at', current_time('mysql', true));
break;
}
}
add_action('created_term', 'update_term_timestamps');
add_action('edited_term', 'update_term_timestamps');
Now the meta data is accessible with:
//for created timestamp...
$timestamp = get_term_meta($term_id, '_term_created_at', true);
//for edited timestamp...
$timestamp = get_term_meta($term_id, '_term_edited_at', true); | stackexchange-wordpress | {
"answer_score": 9,
"question_score": 5,
"tags": "tags"
} |
Difference between fragment caching and wp_cache
I've been really confused about these two caching modes. What's the main difference between fragment caching and wp_cache? Can both of them be used hand in hand?
**EDIT**
I've read about the fragment caching found in the link commented by @Steven. I just want to know what's there difference and which one to use for better performance. | I'll post this as an answer, even though I don't know much about caching.
If you read about WP Object Cache it says:
> By default, the object cache is non-persistent. This means that data stored in the cache resides in memory only and only for the duration of the request. Cached data will not be stored persistently across page loads unless you install a persistent caching plugin.
From what I understand from the article by Ryan Burnette, you can set the caching time yourself.
> Fragment caching takes the output of a code block and stores it so for a predetermined amount of time. When the code runs, as long as the time limit hasn't elapsed, the block is ignored and the stored output is returned and printed onto the page.
We'll know soon if I'm completely off the mark here :) | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "query, cache"
} |
Wordpress custom plugin that uses woocommerce enabled payment gateway for payment
I have a certain special product that I do not want to be listed with other products, nor be added to the cart.
I want that specific product to have a fixed customized page where the user can pay for it immediately using any of the gateways of woocommerce that appears on the same page.
Any help is greatly appreciated. | Ok, it seems to me that there are two different solutions you can try based on preference.
Option #1 would be to add a subdomain to your existing domain and basically set up a landing page for that one product. This way, you would be able to set up a separate Woocommerce on that subdomain and install a plugin like WooCommerce Quick Checkout to bypass the product page and cart page and go straight to checkout.
Option #2 would be to add that same plugin WooCommerce Quick Checkout on your existing site and create a page for that product. This may be the easier of the two options. The plugin can be found here: <
Hope this helps. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development, woocommerce offtopic"
} |
WP theme update causes child theme CSS problems
I have WP website with a child theme installed which I use for css editing. But, after the last update of the WP theme, I noticed little (but annoying) changes in the appearance of my site (for example: nav menu font size is a bit bigger, some images aren't in the correct order, some page's content has too much margin-top etc.)
Do I need to go through the whole process of fixing this problems or is there some way of reversing back to the previous WP theme version? How should I avoid this problem in the future updates? | It may be possible that your theme author would be able to provide you with a previous version of the theme, not sure though. In regards to how you can avoid this issue in the future, I would recommend performing a backup of your Wordpress files before updating anything (this goes for plugin updates, Wordpress core updates, etc). There are a bunch of plugins out there that can help you with running automated or manual backups.
You could also set up a dev subdomain or recreate the site on a local environment and test any changes you want to make there before making them on your live site.
In any case, I would always recommend running scheduled backups of your site to ensure that you can always roll-back in case something goes wrong. In your case right now however, I would start to take a look at your child theme and fix your styling issues that are conflicting with the theme update. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "css, html"
} |
Woocommerce - Show random product thumbnail from specific product category
I am trying to show random product thumbnails from a specific category. I have this code at the moment but it is not working and will show from all products, how to randomize from a specific product category?
<?php
$args = array(
'posts_per_page' => 1,
'orderby' => 'rand',
'post_type' => 'product' );
$random_products = get_posts( $args );
foreach ( $random_products as $post ) : setup_postdata( $post ); ?>
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a>
<?php endforeach;
wp_reset_postdata();
?> | Add a tax_query to your `$args`...
$args = array(
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug', //possible values are term_id, name, slug or term_taxonomy_id
'terms' => 'tshirt' //can be single string or array of slugs, names, term_ids or taxonomy_ids
)
)
);
$results = get_posts( $args );
Recommended reading:
* <
* < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "woocommerce offtopic"
} |
Replace comments with a dummy text
I want to hide comments for a certain time and show a sample text in the comment text area. Say, there are 50 comments on a post. What I want is- hide every comments on this post and there will be a text saying "this comment is hidden". Is it possible?
I am very new with WordPress. | Yes, possible.
Add this to your theme's `functions.php` file-
add_filter( 'get_comment_text', 'replace_comment_texts' );
function replace_comment_texts() {
return "This comment is hidden";
}
I have written a plugin few days back, that does the exact thing. You can try this too- < | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "comments"
} |
Display only text to WordPress loop without loosing the text formatting
I want to display text from content (only text) with the formating (paragraph, bold, italic.) on loop. When I am using this code:
<?php echo mb_substr( strip_tags( get_the_excerpt() ),0,255); ?>
or
<?php the_excerpt(); ?>
The text displayed without the text formating. No p, br even the hr is disappear.
When I am using this code:
<?php echo apply_filters('the_content',substr(get_the_content(),0,550)); ?>
The text displayed with the format, but the other content also display (image, video and else) I just want to display the text with the format.
Anybody know how to resolve the problem? Really appreciate for any help
Thank you | Try this code in your theme's `functions.php` file-
function filtered_content($content){
$content = preg_replace("/<img[^>]+\>/i", "", $content); // removes images
$content = preg_replace('/<iframe.*?>/', "", $content); // removes iframes
return $content;
}
add_filter('the_content', 'filtered_content');
This will remove img and iframe tag from your content. Then use `the_content()` in your template. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "php, loop, filters, text"
} |
call get_header() function from different theme
When i create a new page, i want to choose different theme. I know about Multiple Themes plugin but i'm thinking something else. Install three different themes, activate only one and then creating a new page template in this which calling functions `get_header()` and `get_footer()` from another theme.
I don't know if i can do this but i want to try it.
My question is how to call `get_header()` from another theme? | You can't do it.
Well you can hack it, but it is very unlikely to give you the results you expect as there are usually many settings that needs to be initialized when themes are used and since themes are rarly designed to be able to "run" in parallel with other themes you will have a collision of settings. In addition the `header.php` contains more the the HTML header and the HTML it produce have to be compatible with the HTML and CSS produced by the other parts, something that it is unlikely to happen between different themes. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "customization, themes"
} |
Translating add to cart woocommerce button
I am trying to translate add to cart button. I have 2 code snippets from woocommerce documentation here are they:
FOR SINGLE PRODUCT - THIS ONE WORKS
add_filter( 'woocommerce_product_single_add_to_cart_text',
'woo_custom_cart_button_text' ); // 2.1 +
function woo_custom_cart_button_text() {
return __( 'My Button Text', 'woocommerce' );
}
FOR PRODUCT ARCHIVE - NOT WORKING?
add_filter( 'woocommerce_product_add_to_cart_text',
'woo_archive_custom_cart_button_text' ); // 2.1 +
function woo_archive_custom_cart_button_text() {
return __( 'My Button Text', 'woocommerce' );
}
I dont know why this other is not working. Is there some fix. I am using DIVI wordpress theme. And also overwrote my loop archive addtocart.php so I can display quantity input. This is also snippet from woocommerce documentation. | What is the content contained within your `add-to-cart.php` file template override?
It should be similar to this:
global $product;
echo apply_filters( 'woocommerce_loop_add_to_cart_link',
sprintf( '<a href="%s" rel="nofollow" data-product_id="%s" data-product_sku="%s" data-quantity="%s" class="button %s product_type_%s">%s</a>',
esc_url( $product->add_to_cart_url() ),
esc_attr( $product->id ),
esc_attr( $product->get_sku() ),
esc_attr( isset( $quantity ) ? $quantity : 1 ),
$product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
esc_attr( $product->product_type ),
esc_html( $product->add_to_cart_text() )
),
$product );
In which case, if `$product->add_to_cart_text()` exists, then using `woocommerce_product_add_to_cart_text` should be sufficient enough to achieve the result. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "php, woocommerce offtopic"
} |
Initial offset of number of posts in home page on the posts page
I've got a problem.
Im using WP_query on my static home page, and i've set up an 'archive' page (not like archives/tags etc) as my 'page 2' which has all my other posts on it.
My home page is a total of 13 posts, but I was wondering, on the 'archive' page, how do you offset those 13 posts without explicitly implying 'offset' => 13 in wp_query? It gives me the same results for each archive page I go to.
So I was wondering, is there an 'initial offset' I could use on the archives page? | One way might be to set `posts_per_page` for the query to 13 and then override the `$paged` global (before the query is called) to force it to 2 if it is only 1... eg.
if ( (is_post_type_archive('post')) {
global $paged;
if ( ($paged == 0) || ($paged == 1) ) {$paged = 2;}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "php, html"
} |
WP Media Uploader modal conflicts with Bootstrap modal
I was creating a form in a Bootstrap Modal to allow users to create new posts from the frontend. Everything seemed alright until I wanted to upload a file to the media library or choose one already uploaded:
This opens another modal using JS from the WordPress core. Unfortunately both BS and WP modals are using the same class on the body tag to indicate an opened modal: `modal-open`. When closing the secondly opened (WP) modal, this class is removed from the body which results to unwanted behaviour. You can scroll the document in the background but not the modal itself.
How could one fix this conflict? | Just proxy the `modal-open` class for Bootstrap like this:
.bs-modal-open {
overflow: hidden;
}
.bs-modal-open .modal {
overflow-x: hidden;
overflow-y: auto;
}
// or using sass …
.bs-modal-open {
@extend .modal-open;
}
Add/remove the `bs-modal-open` class to the body when opening/closing a BS modal:
$('.bs-modal')
.on('show.bs.modal', function (e) {
$('body').addClass('bs-modal-open');
})
.on('hidden.bs.modal', function (e) {
$('body').removeClass('bs-modal-open');
});
Finally add the `bs-modal` class to each of your BS modals:
<div class="modal bs-modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
…
</div> | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "jquery, css, javascript, twitter bootstrap, media modal"
} |
How to add credit card validation check to wordpress
Im working on a restaurant reservation website and I need to add a feature similar to one found on booking.com, that is once someone wants to make the reservation I would need them to leave us their credit card information for the restaurant they are booking a table at just in case if they are "no-show". But I need it to be an actual valid credit card, so the system should pull the information from somewhere and make sure it's a real credit card, is there a possibility to make such thing a reality? | If by "valid credit card", you mean a valid credit card _number_ , then that can be done automatically with JavaScript. You're looking for a Luhn algorithm implementation. Here's one I just found on GitHub: <
Otherwise, if you want to validate that it's an active credit card that can support a payment of a certain amount, you'll need to tie into a service like Stripe.
There are jQuery widgets for the Luhn stuff you could add, and doubtlessly WordPress plugins that'll offer Stripe integration. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "plugins, plugin development"
} |
Permalink problem ( Blog posts vs custom post types)
I have add `/blog/%postname%` permalink option for blog posts.
Sample blog post : domain.com/blog/post-name/
I have custom post type called product. Now it permalink display as follow.
domain.com/blog/product/product-name/
I need to use it as domain.com/product/product-name/ . How to do it? (Blog posts should be domain.com/blog/post-name/)
Thanks | You have to set `with_front` to `false` when you register the post type to prevent any static prefix in your permalink structure from being prepended on custom post type permalinks.
$args = array(
'rewrite' => array(
'slug' => 'product',
'with_front' => false
),
// other args...
); | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "permalinks"
} |
Output post thumbnail (add class)
I'm using the following to output the post thumbnail as a marker on a map.
$thumb_id = get_post_thumbnail_id();
$thumb_url_array = wp_get_attachment_image_src($thumb_id, array( 100, 100), true);
$thumb_url = $thumb_url_array[0];
But, I want to add a class to the thumbnail.
I tried `array('class' => 'your-class-name')` but that didn't work. | Use `wp_get_attachment_image()` instead if you want to set a class property.
Example:
$image = wp_get_attachment_image(
get_post_thumbnail_id(),
array(100, 100),
true,
array('class' => 'your-class-name')
);
//returns the HTML for the attachment
echo $image;
The above function returns the HTML `img` tag:
`<img src=" class="your-class-name"/>`
You can see the difference between functions here:
* <
* < | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "post thumbnails"
} |
Does get_template_part() content gets parsed if it's not executed?
My page templates are currently built up as shown in first example but I really don't like that half of the template is _just sitting there_ , not being used and takes the server resources for no good reason.
**Does everything in both examples gets parsed by server, emphasis on`get_template_part()`?**
* * *
<?php
//Page template
if( $something ) {
// 1000 lines of code
}
else if( $something_else ) {
// 1000 lines of code
}
?>
* * *
**_versus_**
* * *
<?php
// Page template
if( $something ) {
// Template with 1000 lines of code
get_template_part( 'lib/template', 'option-a' );
}
else if( $something_else ) {
// Template with 1000 lines of code
get_template_part( 'lib/template', 'option-b' );
}
?> | Only if `$something` or `$something_else` are true, otherwise the code will jump to the next argument. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "page template, get template part"
} |
Where to enqueue stylesheets for plugin?
I want to enqueue stylesheet to plugin I'm developing, like this:
function utm_user_scripts() {
$plugin_url = plugin_dir_url( __FILE__ );
wp_enqueue_style( 'style', $plugin_url . "/css/style.css");
}
add_action( 'wp_enqueue_scripts', 'utm_user_scripts' );
I am adding this code in the main file, [plugin_name].php.
Nothing is loaded, which part am I doing wrong? | Add this code in your main file: [plugin-name].php:
function utm_user_scripts() {
$plugin_url = plugin_dir_url( __FILE__ );
wp_enqueue_style( 'style', $plugin_url . "/css/style.css");
}
add_action( 'admin_print_styles', 'utm_user_scripts' );
So basically, you need to use 'admin_print_styles'. At least it did the trick for me. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "plugin development, wp enqueue script"
} |
Unified search across separate WordPress installations
I have many (100+) different WordPress installations across different servers and I'd need to have a centralized search... engine? to be able to search in all of the websites at once. I'm not running WordPress Multisite and installing it is not an option. Moving all the sites to the same server isn't an option either.
I've been researching for solutions and I've come across both ElasticSearch and Apache Solr, both seemingly built on top of Apache Lucene. There seems to be plugins for both systems, but none of them mention multi-website search.
How could I set this up? Do you have experience setting a search across multiple WordPress installations? | At the end I've eventually done what I initially posted in the question. I've set up an Elasticsearch server using Docker, and I've installed the Elasticpress plugin, which properly indexes all the posts and pages in the elasticsearch index.
Then, I've created a simple front-end to search in Elasticsearch using simple bootstrap and jquery and it works like a charm. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 6,
"tags": "search"
} |
Anchors in WordPress not followed/ indexed in sitemap.xml
Have anchor tags on a WordPress page about 300 on a page which are not listed in sitemap.xml, these links are generated dynamically. How do I index these?
Structure: A navigation link say **Games** when clicked --> Opens **List of Games (Football, Basketball etc.)** when clicked Football it opens --> Different versions of the games.
These are not listed in the sitemap.xml when created from online sitemap generators.
When clicked them manually in pages they open but doesn't appear in sitemap.
Any help would be great. Thanks! | Google does not index anchor tags, only URLs. (Note that by anchor tags, I assume you mean a URL like **site.com/page.html#anchor** )
The solution is to create a separate, static URL that displays the same content as what you would get with the anchor tag - for instance **site.com/page-anchor.html**.
Then you can just create a page with links to all these new URLs, and Google will follow those links nearly as efficiently as with a sitemap file. Or manually edit a sitemap.xml file and upload it to your server for Google to index. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "seo, nofollow, google xml sitemaps"
} |
A question about register_activation hook
Looking at wp codex it says:
**The register_activation_hook function registers a plugin function to be run when the plugin is activated.**
I am finding this to be not entirely correct, for example i can activate a plugin that adds an extra field to WP registration form (using the add extra field example in codex) which does not require the register_activation_hook function (nor the register_deactivation_hook).
What codex does not tell you is when and when not to use the register_activation_hook, now i am going to guess that the hook is only required when including files for install or creating db tables on plugin activation, i would be grateful if someone who has more knowledge of WP and the correct use of the register/deregister hooks could clarify its correct usage.
regards | The `register_activation_hook()` is actually just a wrapper for `add_action('activate_' . $file, $function);` and is only executed when a plugin is activated.
This action/function is meant to be used by anything that should only execute once when the plugin is activated, things which would include stuff like
* adding custom terms to taxonomies
* create new database tables or rows
* running one time db processes which might include updating certain tables, columns or rows
* flush rewrite rules
On the opposite, `register_deactivation_hook()` only executes when a plugin is deactivated. This hook/function/action is meant for running processes to clean up after the plugin, which may include
* restoring db tables, row or columns which was altered
* removing custom db tables which was added by the plugin
* removing any custom options which was added by the plugin that would not be necessary anymore | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "plugins, activation"
} |
Create page options for theme?
Is there any "default" possibility to create page options for theme? I found only some page builder like visual composser etc... but I need it only for page options like set social links or colors... | Using the WP_Customizer API you can create you own options and settings. The WP_Customizer is simple to use, create the section, define the setting and the control. Then go to the customizer page and you can set values. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "themes"
} |
Resposive admin classes?
Does WordPress have default classes that makes possible to use several _(resposive)_ columns in admin area / meta boxes? Take a look at the example below: I need inputs to be in separate columns.
Yes, I could do it myself but I find it poinless to load more `CSS` if WP already has the functionality.
* * *
**HTML code:**
<p>
<label for="first">This is first input</label>
<br/>
<input type="text" name="first" id="first" value="" size="30" />
<label for="second">This is second input</label>
<br/>
<input type="text" name="second" id="second" value="" size="30" />
</p>
* * *
**How it currently looks like:**
; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 1,
"tags": "php, custom taxonomy, post thumbnails, post meta"
} |
Several nonces?
Is there a point having several nonces? Does it increase the security?
_E.g adding nonces to meta boxes while`<form>` (which is basically the whole add/edit post screen) already has one by default._
* * *
* Docs, tutorials and old answers all insist adding nonce when you'll make a custom meta box
* Like I said, WordPress already adds a nonce to `<form>` by default
* Only I _(admin)_ has access to admin area, everybody else gets redirected
* I would prefer not to add nonce to every meta box codeblock - adding complicated meta boxes is **a huge amount of code** even without it
**How is it then?**
* * *
Optional bonus question: How about field sanitizing, validation? If nobody else has access.. | No, there isn't any point in that.
All docs relating to metaboxes are probably inspired from the wrong code at the codex which use a nonce.
The problem which nonces in metabox inadvertently solve is avoiding data corruption when the quick edit feature of the posts list page is used (or thinking about it any sort of external API as well), as at that point there is no metabox and no data in the form. This can be tricky especially if you have checkboxes in the meta box, but the better way to solve it is by having an explicit hidden input that will indicate that the metabox was displayed (basically this is what the nonce does but it is confusing as it has nothing to do with security).
As for sanitation and validation, you should always do it, because users can send bad values to your code which might even be a legal input. It helps with security but it is not the only reason you should do it - < | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "nonce"
} |
How to tell which database tables belongs to which multisite site
I have a local multisite installation I use for development with a relatively large number of sites set up. Every site has its own numbered database tables (i.e. `wp_n_links`, `wp_n_options`, `wp_n_postmeta` etc.)
Every time I need to look at a database table in phpMyAdmin I have to look through all the `wp_n_options` tables to find the tables for the site I need and with a lot of sites this can get a bit tedious!
Is there a better way to find out which tables belong to which site? | The number you refer to is the blog/site ID, so you have multiple methods of finding out which site it is:
* Look in the sites table, the number should match the ID, providing you with a URL and title
* Go to example.com/wp-admin/network/site-info.php?id= _insert-number-here_ and you'll be shown the network admin UI for that site
* Consider a plugin or custom column in the sites area of the network admin that displays the blog ID | stackexchange-wordpress | {
"answer_score": 7,
"question_score": 8,
"tags": "multisite, database"
} |
Exclude post on loop by multiple meta key value
I need to exclude the loop two post with different values in your meta key (the same). I investigating got this code that works fine if I enter only one value in `value =>`. But if I want to enter two values it gives me error.
$args = array(
'cat' => 1,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'Caja',
'compare' => 'NOT EXISTS'
),
array(
'key' => 'Caja',
'value' => array('UNO','DOS'), // Here I return an error php: Warning: trim() expects parameter 1 to be string, array given
'compare' => '!='
),
),
);
I used this post as a reference.
Any ideas? | Straight from the codex
> **`value`** (string|array) - Custom field value. It can be an array only when compare is 'IN', 'NOT IN', 'BETWEEN', or 'NOT BETWEEN'.
## SOLUTION
Change `compare' => '!='` to `compare' => 'NOT IN'` | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "wp query, loop, meta query"
} |
How to ignore wp_link_pages function?
I've bought a wordpress theme. I want to ignore all wp_link_pages functions from theme files. I will write my custom codes.
Is there any way to do it with functions.php | `wp_link_pages` has two filters you can use:
* The `wp_link_pages_args` filter is passed the `$args` for `wp_link_pages` so you could set `echo` to false.
* The `wp_link_pages` filter is passed the output so you could set the output to nil. Something like this should work:
/**
* Filter the HTML output of page links for paginated posts.
*
* @param string $output HTML output of paginated posts' page links.
* @param array $args An array of arguments.
* @return string $output HTML output of paginated posts' page links.
**/
add_filter('wp_link_pages', 'wpse_218590_hide_wp_link_pages', 10, 2);
function wpse_218590_hide_wp_link_pages( $output, $args )
{
return '';
}
_This isn't tested and I only had a quick look at the filters so it may not be 100% correct but it should give you an idea of what to do_ | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wp link pages"
} |
Why does get_template_part() break variables?
In PHP, when you `include` a file, the variables you're using in your current scope are available for use in the included file.
When using WordPress's `get_template_part()`, variables are no longer available in the "included" file.
`get_template_part()` calls `locate_template()` which then calls `load_template()`, which then performs the `require` or `require_once`.
If WordPress eventually calls PHP's `require`, why do the variables no longer work? Is it something to do with the 3 function calls before the actual `require`? | A script loaded within a function call will only work within the immediate scope of where `require` or `include` was used. So really only variables present when `load_template()` is called will be accessible to the loaded script (unless you use `global $myvar` of course).
The reason vars like `$post` and `$wp_query` are available to the script is because `load_template()` globals them in before loading the script.
If you wanted to make sure your script can access certain vars, either `global` them in or add them to the `$wp_query->query_vars` array before loading ( _not recommended but depending on the task it might be the only feasible option_ ), as those get extracted into the local scope before loading the script. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 2,
"tags": "include"
} |
Modify Genesis Custom Header CSS
I am using the Associate Theme based on the Genesis framework and I'm trying to use a background image and background colour in the header. Genesis seems to dynamically generate the CSS for this and I get:
.custom-header #header {
background: url( no-repeat !important;
}
What I need is to change this to:
.custom-header #header {
background: white url( no-repeat !important;
}
I cannot find where to do this and un-hooking the genesis header and manually coding it in seems to defeat the object of using the framework.
Does anyone know how I can achieve this, please? | Hook onto the same action as the genesis header function and kick out your overriding CSS:
function wpse_218701_genesis_header() {
?>
<style>
body.custom-header #header {
background-color: white !important;
}
</style>
<?php
}
add_action( 'genesis_header', 'wpse_218701_genesis_header' ); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "genesis theme framework"
} |
add_filter adds output in the head
I build plugin and I have a problem
I add to plugin:
add_filter( 'the_content', myFunction);
function myFunction()
{
$options = get_option('myPlugin_settings');
if (is_page($options['myPlugin_list'])) {
echo"--------------------------------------------------------";
}
}
and I see the `--....` also in the head.
Why is this happening? | Filters should `return` their content, and not `echo` it. That is why you see the output in your head as well
## EDIT
I really have no idea why you would want to use `require` or `include` in your filter.
Here is an example of your filter should be coded
add_filter( 'the_content', myFunction );
function myFunction( $content )
{
$options = get_option('myPlugin_settings');
if ( is_page( $options['myPlugin_list'] ) ) {
return "--------------------------------------------------------";
}
return $content;
} | stackexchange-wordpress | {
"answer_score": 5,
"question_score": -1,
"tags": "plugin development, filters, the content"
} |
Fatal error: Call to undefined function post_exists()
I am using the function in my own class as I am using other wordpress functions in it.
I am unable to understand why it is not able to find the function while ide "go to declaration" point me to file wp-admin/includes/post.php
is wp-admin files functions do not exist as global. | The files in `wp-admin` are only loaded when you're in the admin area... when you're looking at pages or posts those functions aren't loaded. In that case you'd need to require the file first, so you'd want to do something like this in your function:
if ( ! is_admin() ) {
require_once( ABSPATH . 'wp-admin/includes/post.php' );
}
The `if ( ! is_admin() )` part is important because WordPress includes the file automatically when `is_admin()` is `true` so you only want to include it if `is_admin()` is `false`. Also make sure to include this snippet _before_ you try to call the `post_exists()` function.
If that doesn't work then try this:
if ( ! function_exists( 'post_exists' ) ) {
require_once( ABSPATH . 'wp-admin/includes/post.php' );
} | stackexchange-wordpress | {
"answer_score": 18,
"question_score": 4,
"tags": "posts, functions, errors"
} |
ACF check if variable has http, if else return string
Trying to check if `$link` has ` in front of it or not. If someone puts in `www.google.com` for the link field it acts as a link within the WordPress site, ie: `www.website.com/www.google.com`.
$link = get_field('advertisement_link');
$ad_code = '<a href="'.$link.'" target="_blank">Test</a>';
Sample code above I am working with. This is a general PHP question as well. How do I do this the right way? Tried below, replaces `the_content()` with the `$link`.
$link = get_field('advertisement_link');
if(strpos($link, ' !== 0) {
return ' . $link;
} else {
return $link;
}
$ad_code = '<a href="'.$link.'" target="_blank">Test</a>';
Edit: I need to keep `$ad_code` because I'm using it inside `return prefix_insert_after_paragraph( $ad_code, 3, $content );` to insert this ad into a post every 3 paragraphs. | You must not `return` the value, but alter the varialbe `$link`
if(strpos($link, ' !== 0) {
$link = ' . $link;
} //no else needed
Be aware that if your link begins with ` it will also prepend the ` and result in `
The better way to do this would be from here, adjusted to your needs:
In `functions.php`:
function addhttp($url) {
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = " . $url;
}
return $url;
}
Code for you:
$link = addhttp( get_field('advertisement_link') );
$ad_code = '<a href="'.$link.'" target="_blank">Test</a>'; | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "php, advanced custom fields"
} |
show ad after # paragraphs
Trying to use ACF to determine when to insert an ad after # many paragraphs. Right now after `3` paragraphs the ad is inserted.
if ( is_single() && ! is_admin() ) {
$show_after = get_field('show_after');
return prefix_insert_after_paragraph( $ad_code, 3, $content );
}
I'm having issues mapping `3` to the variable `$show_after`. Returns nothing in below code:
if ( is_single() && ! is_admin() ) {
$show_after = get_field('show_after');
return prefix_insert_after_paragraph( $ad_code, $show_after, $content );
}
Is there any way I can map the `3` to a variable so the poster can input the paragraph amount? | You need a `post_meta` field to let an author decide after how many paragraphs the ad is inserted, if you want to do it like that, and not with a shortcode.
So create a custom field called `f711_insert_after_no_p`, and use your function like this:
if ( is_single() && ! is_admin() ) {
$show_after = get_field('show_after');
return prefix_insert_after_paragraph( $ad_code, get_post_meta( get_the_ID(), 'f711_insert_after_no_p', true ), $content );
}
Be sure to validate the input to only allow integers, or do this in the output.
I think for ACF the code (instead of `get_post_meta( get_the_ID(), 'f711_insert_after_no_p', true )` ) would be
get_the_field( 'f711_insert_after_no_p' ) | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "post meta"
} |
Do I need to escape data passed to wp_localize_script()?
Title pretty much says it all. I took a look at the source, and I didn't see any escaping being done. But, I can't say for sure.
wp_localize_script( 'script-hook', 'object_name', array(
'param_1' => $value_1, // This?
'param_2' => esc_js( $value_2 ) // Or, this?
) ); | As far as I know `wp_localize_script` doesn't escape data any more than is necessary to produce valid JSON, and everything is sent as a string. The function was originally designed to allow translating the strings used in your JS into other languages (hence the "localize" part of the function name). So if the data you're passing is coming from a user input or is otherwise user-generated then you'll definitely want to escape it. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 5,
"tags": "wp localize script, escaping"
} |
woocommerce Product shortcode create
i am very new wooCommerce and WordPress. programming knowledge not strong yet. but for my project i need to do something. now i want to create custom short code for woocommerce product.
i want to show product by id or sku. woocommerce built-in shortcodes have and it is working fine which is < but example `[product id="99"]` but if use this shortcodes then it come with add to cart price etc information. mean template take for product. but i want to show only thumbnail picture and name and link. how can i do that ? can do anything in function.php for this. or create separate shortcodes for this.
would you guys help me out . how can i do that.
Thanks | Hello Here is the Shortcode you can use this it will give you title link and image of product. Put this code in functions.php file of your theme.
add_shortcode('product_data','custom_product_function');
function custom_product_function($atts)
{
$post_id = $atts['id'];
$title = get_the_title($post_id);
$link = get_the_permalink($post_id);
$image = get_the_post_thumbnail($post_id);
$data ='<div><a href="'.$link.'"><p>'.$title.'</p></a>'.
$image.'</div>';
return $data;
}
And then add the shortcode in your page or post with product id
[product_data id=1958] | stackexchange-wordpress | {
"answer_score": 3,
"question_score": -1,
"tags": "shortcode, woocommerce offtopic"
} |
Parent comment's author name
` function to display the comment author's name:
// Display the parent comment author's name:
if( $comment->comment_parent )
comment_author( $comment->comment_parent );
and the `comment_author_link()` function to display the comment author's link:
// Display the parent comment author's link:
if( $comment->comment_parent )
comment_author_link( $comment->comment_parent ); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 4,
"tags": "comments"
} |
How to solve a translation function issue with no arguments and missing a text-domain?
I have a warning via WordPress Themecheck plugin WARNING : Found a translation function that is missing a text-domain. Function esc_html__, with the arguments
As you can see, there is no arguments listed above and I'm really lost on this.
Here's the code function:
<?php
wp_nonce_field( basename( __FILE__ ), 'matilda_featured_image_nonce' );
$selected = esc_html__( get_post_meta( $object->ID, 'matilda_featured_image', true ) );
?>
My text domain is "matilda"
Thanks for any suggestion. | Seems like the right thing to do there is to call `esc_html` instead of `esc_html__`. I have a feeling you don't need any escaping there at all. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "translation, textdomain"
} |
Exclude the content before "the more" on single posts
I have a post with text then "the more" then text after that.
The teaser before the more displays on the archive page, but I don't want to display it on my single post page, only the text after the more should appear.
How do I do this?
i.e
This is my text before the more don't show it.
\--The More--
Text after the more to be displayed on single page. | You probably looking at something like `get_extended()`. It returns the content in an array with the following key=>value pairs
* `main` => The content before the more tag
* `extended` => The content after the more tag
* `more_text` => The custom read more text
So you would want to do the following in your single post page inside the loop
$content = get_extended( $post->post_content );
$extended = apply_filters( 'the_content', $content['extended'] );
echo $extended; | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 0,
"tags": "read more"
} |
Creating a user from a different website
I need to create users for `example.com`, however I only have access to `dev.example.com`'s dashboard now. Can I still create them for `example.com` from `dev.example.com`'s dashboard? (I see a "website" field on the "Add New User" form but unsure what it's for) | No, you cannot create a user on another install - you need access to the main site (either via WordPress admin or the database).
The "Website" field on the "Add New User" form is nothing more than a profile field for storing information about the user (in this case, a URL). | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "users"
} |
How i make a custom sql query for Woocommerce
hello i have an ecommerce with Wordpress + Woocommerce, just yesterday a hacker boy or...i don't know moved all woocommerce products in to the trash.... there are lots of products and default wordpress bulk edit didn't work propelly,
so i think make a custom slq query for edit wp_posts table and post_status from trash to publish, how i can do it, any help please?
Thank you all in advance | I am not good at SQL but I believe this SQL query will do the job for you.
UPDATE wp_posts
SET post_status = 'publish'
WHERE post_type = 'product' AND post_status = 'trash';
Please remember to change WP database prefix if it is not default `wp`. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "query, woocommerce offtopic, sql"
} |
Retrieve all users from wordpress database via REST/JSON API
I've read that the WP REST API v2 retrieves only users that have made a post for the blog. I'm developing an iOS and Android app that needs to use the Wordpress registration.
How I could retrieve a list of all users registered to my Wordpress blog? Even those that never wrote a post? | Thanks to stackoverflow user Milap !
You can get all users even they have not created any post, for that you need to modify rest-api plugin.
Open `wp-content/plugins/rest-api/lib/endpoints/class-wp-rest-users-controller.php` file, you will find below code on line number 106,
if ( ! current_user_can( 'list_users' ) ) {
$prepared_args['has_published_posts'] = true;
}
Change it to below,
if ( ! current_user_can( 'list_users' ) ) {
$prepared_args['has_published_posts'] = false;
}
If you don't want to modify plugin, put below code into current theme's functions.php file.
add_filter( 'rest_user_query' , 'custom_rest_user_query' );
function custom_rest_user_query( $prepared_args, $request = null ) {
unset($prepared_args['has_published_posts']);
return $prepared_args;
}
You are done.
FYI: i choose to edit the API file and it worked. | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 5,
"tags": "users, plugin json api, rest api"
} |
How to increase execution time out limit in WordPress dashboard?
One of my plugins creates a time out every time I visit the `Products` admin page in my `WooCommerce` website dashboard. I can't deactivate this plugin as it's absolutely essential for what we do. Any way to increase time out limit? | You can increase your max execution time by adding the following to your .htaccess
php_value max_execution_time 300
Otherwise update your php.ini file to reflect the max execution time increase. | stackexchange-wordpress | {
"answer_score": 3,
"question_score": 0,
"tags": "woocommerce offtopic, performance"
} |
Woocommerce resize existing product images
We discover that our Single Product images as set in Woocommerce> Setting > Products > Display are set to big. Single Product Image: 500 ×750px xHard Crop
I have tested plugin regenerate thumbnails but that does not work on the product images. Also test plugins Resize-image-after-upload. But that plugin does it for all images if bigger then a certain size. So not to use either. Try to get a plugin or functions.php code to re-size all existing product images to the right dimension. Without luck.
Question: Do you know a plugin or php code for functions.php that does resize all full product images?
Would be very helpful. | I use this one for rebuild thumbnails: < | stackexchange-wordpress | {
"answer_score": -1,
"question_score": -1,
"tags": "plugins, woocommerce offtopic, images"
} |
Custom Post Type within the Loop on Homepage (Page Template)
I'm trying to achieve something with the Loop and CPT. I've built a template page which will be the homepage of my website displaying articles and videos (the CPT). How can I add the CPT within a loop so it displays both in order as sort of a feed?
I've added the snippet below to `functions.php` :
// Custom loop feed
add_action( 'pre_get_posts', 'add_my_post_types_to_query' );
function add_my_post_types_to_query( $query ) {
if ( is_home() && $query->is_main_query() )
$query->set( 'post_type', array( 'post', 'videos' ) );
return $query;
}
And then put the code for the loop in my `homepage.php`.
Thing is, it displays it on my blog page, but on my homepage it made a post for the homepage.
` with `is_ftont_page()`. Read here for the difference between the two.
If that doesn't fix your issue, you could try making a call to WP_query from within your template code. It might look something like this:
$query = new WP_query(
array(
'post_type' => array('post', 'videos'),
'post_status' => 'publish',
'order' => 'ASC'
)
);
foreach ($query->posts as $post) {
// Your display code here.
}
There are a lot of parameters that you can modify to get the query working just the way you want it. It's all there in the documentation. If you go this route, you would want to remove the 'pre_get_posts' hook.
Hope this helps! | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "custom post types, loop, homepage"
} |
How to filter by date & a specific custom post type post-WP 4.4?
WordPress 4.4 introduced the ability to display date archives by appending /?post_type=custom_post_type to the end of the date url. i.e. localhost/2016/02/?post_type=news.
I had assumed I could do: `if( is_post_type_archive('news) && is_date())...`
But from what I can discern:
* is_date() will only detect if the page is displaying a year/month/day archive & is_date() applies to all CPT date archives as well
* is_archive() applies to all archive pages
* is_post_type_archive('CPT') will only apply to the archive page and filters out date archives
I'm trying to output a menu on the news date archive pages to display separately from the blog date archive pages. | There is no logical explanation why `if( is_post_type_archive('news) && is_date())` should fail and not work in your situation.
* `is_date()` return true on all date archives
* `is_post_type_archive( 'news' )` will return true on post type archives
When you visit `localhost/2016/02/?post_type=news`, both of those ring true, and they will only ring true on that specific URL
If it it fails, you have something breaking your main query, maybe a bad `pre_get_posts` action or you are using `query_posts` somewhere on the page which will break the main query object. You should do `var_dump( $wp_query )` and inspect the main query object. Specially look at `$query` property | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "archives, date, custom post type archives, wp get archives"
} |
Password protected uploaded PDF page
I created a custom post-type called "designs" for this case. So I want the client to go to his backend and click "Create new Design", this will open up the create page screen, now I want my client to have the option to just upload a number of PDFs and I want to be able to put those PDFs in a layout I desire.
Right now, with wordpress' default behaviour the user can upload PDFs but they will appear as text links and he can just add his own formatting of the page in the editor.
So my question boils down to this: 1) how am i able to limit the user to just inputting his PDFs and thats it?
Bonus question: Is it also possible to somewhere state implicitly that the PDF has to open in a new tab? | Try using the Advanced Custom Fields plugin: <
You can add a file(s) upload field to your "designs" post type, and hide the regular content editor. Then you can create a custom template for that post type that displays the files attached to the post. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 0,
"tags": "uploads, editor, pdf"
} |
Custom Excerpt is returning 52 characters and not 52 words
I have this custom function that get's the manually entered excerpt and trims it down but the problem I'm having is that it is trimming the characters down to 52 and instead I want it to return the first 52 Words like the normal excerpt.
Here's the custom that allows me to trim the manually entered excerpt
function themeTemplate_trim_excerpt( $content ) {
return substr( strip_tags( $content ), 0, 52 );
}
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'template_trim_excerpt');
This is the only way I've been able to cut the manually entered excerpt.
How do I make it trim it so it only shows the first 52 words?
Thanks for any feedback :) | The function you want is **`wp_trim_words()`**, example:
function themeTemplate_trim_excerpt( $content ) {
$more = '...'; //where $more is optional
return wp_trim_words($content, 52, $more);
}
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'template_trim_excerpt'); | stackexchange-wordpress | {
"answer_score": 4,
"question_score": 2,
"tags": "excerpt"
} |
Convert HTML5 to Wordpress theme
I designed a HTML5 template. Now I want convert that template to a WordPress theme. I was converting the main page (index.php). Now I want two pages, one to create a section in my theme for a blog which shows a summary of the posts (4 lines from each posts). The other one for showing that post open with all lines and all attachments.
P.S.: I designed those pages in HTML. Now I just want to make that connect to WordPress | You should start with tutorials on web to convert HTML5 to WordPress. The steps are too exhaustive to be covered in an answer here. However, here's a link for you to get started.
Also, don't forget to check out WordPress Codex, the documentation which will guide you through WP functions, standards & APIS. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": -1,
"tags": "posts, theme development"
} |
Best way to change the blog page post type?
what is the best way to change the wordpress blog page post type. by default it fetches the posts with post type is equal to posts but how we can change to to lets say posts type is equal to blog. One way is to add the costume query on the index.php page and selecting the specific post type. Is there any other effective way of doing this ? | You may edit the query using the pre_get_posts action. You can do something like this:
add_action('pre_get_posts','wpse_218948_search_filter');
function wpse_218948_search_filter(){
if( is_page('blog') /* or whatever page it is */ && $query->is_main_query() ){
$query->set('post_type', 'blog'); # query post type "blog"
$query->set( 'posts_per_page', -1 ); # display all posts
}
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "custom post types, blog page"
} |
PHP include statement not working?
Just started learning PHP and Wordpress.
Why isn't my PHP include statement working in the following `header.php` file?
<!DOCTYPE html>
<head>
<meta charset="<?php bloginfo('charset'); ?>" />
<title>
<?php include 'functions.php';?>
<?php if( is_page(1406)): ?>
<?php wp_title(' - ', true, 'right'); ?> <?php get_1406_page_title(); ?>
<?php else: ?>
<?php wp_title(' - ', true, 'right'); ?> <?php bloginfo('name'); ?>
<?php endif; ?>
</title>
.
.
.
I need to call `get_1406_page_title()` which is located in the `functions.php`. The above code produces empty page, and when I remove the include line the title is empty.
Here is the `get_1406_page_title()` from `functions.php`:
function get_1406_page_title()
{
$title = "Page title here";
return $title;
} | From your current code you
* do not need to include `functions.php`, it is automatically done
* Because `get_1406_page_title()` returns it's output, you need to echo the result from the function if you need to display the result
echo get_1406_page_title(); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "php"
} |
Remove description from <title> on Home
My theme has support for title-tag `add_theme_support('title-tag')`, but I can't remove the wordpress description `bloginfo('description')` from `<title>` on Home page.
I'm trying using this filter with no success:
add_filter( 'wp_title', function ( $title, $sep ) {
global $paged, $page;
$title .= get_bloginfo( 'name' );
if ( is_home() || is_front_page() )
$title = "$title";
return $title;
}, 10, 2 ); | Found a solution:
add_filter( 'pre_get_document_title', function ( $title ) {
if(is_front_page()){
$title = get_bloginfo();
}
return $title;
}); | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 5,
"tags": "filters, title"
} |
Fixed button and slideshow in template upload per page
For all products there is a different page. Every product page will have the product template. On this template I'll have 3 download buttons and a slideshow. Now I want that when making a page for a product that there is a option to upload 3 PDF's (for the download buttons) and up to 5 pictures for the slideshow.
To give an example Page 'Blue car' will have blue_car_tech.pdf, blue_car_engine.pdf and blue_car_doors.pdf. The page also will have 5 pictures of the blue car for the slideshow. Page 'Red car' will have the same but in red.
Now when making the product page I want to select the product template and then there should be 3 button where I can upload the PDF files, and a button to upload the pictures of the products.
I really have no idea how to do this (or something what looks like this), so I was hoping you guys could give me a push in the right derection. :) | You should try <
With this plugin you can easy add extra fields to the backend of a page. You can also set it to show only when a specific template is selected. | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "theme development"
} |
Filter authors on meta value
I have added a section to my user profiles called ArtistCategory. This can be value X or Z.
I'm using the code below to get a list, which I use in a menu and show after the artists display_name the artists ArtistsCategory. So far so good.
<
I would like to filter the query by only showing authors from ArtistsCategory X and can't get it figured out. All things I can find are post related. Hope someone can help me out on this. Thanks! | Is there a specific reason you aren't using WP_User_Query? It would make it easier to do what you want to. You can read up on it here.
Something along these lines would solve your problem, as far as I understand it:
$args = array(
"meta_key" => "ArtistCategory",
"meta_value" => "X" //or "Z"
);
$authors = new WP_User_Query($args);
if (!empty($authors)) {
echo '<ul>';
foreach ($authors as $author){
//However you want to echo each author.
}
echo '</ul>';
}
else {
echo 'No authors found';
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "filters, wpdb, list authors"
} |
Where/how are categories stored?
Disclaimer: I am new to WordPress.
When I add categories to my blogging site, where/how are these categories stored? If I want to change the names of these categories in batch, without having to go through the point-and-click UI, how would I go about it? Would this be done through a command-line interface? | There is extensive documentation on the database structure of WordPress in the Codex. Its pretty simple but still you probably do not want to mess with the data directly.
As you mentioned CLI I'd recommend WP-CLI which offers some commands you need. A quick example from the docs to change the name of the `term` with the `ID` `15` from the taxonomy `category` to `Apple:
wp term update category 15 --name=Apple | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 5,
"tags": "categories, command line"
} |
How to prevent uppercasing of menu titles
My category names are being converted to uppercase when I use them as menu items.
Here's how I created a category:

'comment_field' => '<p class="comment-form-comment"><label for="comment">' . _x( 'Comment', 'noun' ) . '</label><br /><textarea id="comment" name="comment" aria-required="true"></textarea></p>',
);
comment_form( $comments_args ); | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "comments, comment form, comments template"
} |
Split post title for styling
I need to split up post title and want customize both strings,
For example post title is `This x That`
I need to display this title as **`This x`**`That`. Is there any way to display like that? | Will the format always be as you described? I.e. can we use 'x' as a delimiter to split your title? If so something like this would work:
add_filter( 'the_title', 'wp123_custom_title_format', 10, 2 );
function wp123_custom_title_format( $title ) {
// if you only want to modify certain posts you can do a check here
// use 'x' as your delimiter
$pieces = explode( "x", $title, 2 );
if ( 2 == count( $pieces ) {
$title = '<span class="boldtext">' . $pieces[0] . ' x </span>';
$title .= '<span class="normaltext">' . $pieces[1] . '</span>';
}
return $title;
} | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "posts, wp title"
} |
Divert http to https with WordPress on IIS
I have a WordPress site **running on IIS**. The site has an associated SSL Certificate. Right now I am able to access the site with http and https.
How can I get my http to redirect to https?
Any help would be greatly appreciated.
Thank You | You'll need to update all of the URLs in your database to the HTTPS protocol:
1. Go and download Interconnect IT's Database Search & Replace Script here
2. Unzip the file and drop the folder where your WordPress is installed (the root) and rename the folder to **`replace`** (screenshot)
3. Navigate to the new folder you created in your browser (ex: ` and you will see the search/replace tool
4. In the " _search for…_ " and " _replace with…_ " fields:
* **Replace** : ` (non-HTTP)
* **With** : ` (HTTPS)
You can click the _dry run_ button under _actions_ to see what it will be replacing before you execute the script. Once you're done be sure to remove the `/replace/` folder.
Additionally, you can also look into using the Remove HTTP plugin which automatically scans your website and removes both HTTP and HTTPS protocols from your URL links. This will resolve mixed content warnings. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 1,
"tags": "ssl, https, iis, http"
} |
Keeping shortcode-generated widget and theme element in one line
I set up a playground site PlaygroundSite
and I am trying to put Polylang language changer widget in the same line as linked-in icon. Because ascent theme does not contain a widget/sidebar area there, I used amr shortcode any widget plugin to insert shortcode function into header.php.
Unfortunately, you it does not work OOTB and you can see results on site. I also would love to get rid of that bullet (indicator) on the left of the flag.
The code I use for inserting:
<?php echo do_shortcode('[do_widget id=polylang-4]'); ?> | To get rid of the bullets and change the alingment you'll need CSS.
For the top portion:
aside.widget_polylang.amr_widget,
aside.widget_polylang.amr_widget ul,
aside.widget_polylang.amr_widget li {
/** align with li */
display: inline-block;
float:right;
/** remove bullets */
list-style: none;
}
ul.social-icons {
/** align with li */
display: inline-block;
float: right;
}
For the bottom portion:
aside.widget_polylang li {
/** remove bullets */
list-style: none;
} | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "widgets, sidebar, plugin polylang"
} |
Avoid the removal of "https:" from URLs
WordPress is changing all my URLs from:
to:
//www.example.com/...
For example:
<link rel="canonical" href="//www.example.com/"/>
I don't want this to happen, because it has some side effects with CDN rewriting, and my site is https only.
What is the best way to disable this "feature"? | It was caused by CloudFlare https (which doesn't set the `$_SERVER['HTTPS']` variable), I solved it by forcing:
$_SERVER['HTTPS'] = 'on';
in the webserver configuration. After doing so I could also disable the CloudFlare Flexible SSL plugin, and get a little performance gain. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": 1,
"tags": "urls, https, site url"
} |
How can I add an extra WooCommerce hook
In the standard WooCommerce template file `content-single-product.php` there is a set of hooks that control the way the page lays out in a series of blocks which are called by a series of hooks eg `'woocommerce_before_single_product_summary'`. If you are familiar with WooCommerce you will know what I mean.
There are three of these
* `woocommerce_before_single_product_summary`
* `woocommerce_single_product_summary`
* `woocommerce_after_single_product_summary`
For my layout I need to add a fourth along the lines of `'woocommerce_before_single_product_intro'`
I understand that I can move content around, such as moving the title to before the image. That seems to work fine, but I can't work out how to add a new hook.
I have tried adding `add_action( 'woocommerce_single_product_intro', 'woocommerce_template_single_title', 5 );` to my functions file but it didn't work and I am guessing I have missed something rather important from it. | You can create a hook by calling do_action, then referring to the hook in your `functions.php` with add_action.
For example, in the theme, _where you want the action to occur_ :
do_action('woocommerce_before_single_product_intro');
Then in `functions.php`
add_action('woocommerce_before_single_product_intro','your_function',[...]);
For the sake of maintainability, I'd choose a naming convention that doesn't confuse your hooks with WooCommerce's. | stackexchange-wordpress | {
"answer_score": 5,
"question_score": 3,
"tags": "functions, hooks, woocommerce offtopic"
} |
How to determine if WP_DEBUG is enabled?
I believe I saw this done in a few plugins before, but it has been awhile and I have no clue what plugins offered this or how they offered it, but what I am trying to achieve is this...
I want offer a developer mode for my custom theme I'm creating.
I am running a function that if enabled will load the prettified files instead of the minified files for developers. But, I also want to load the prettified files if WP_DEBUG is enabled.
Is there a way I can check if a user has WP_DEBUG enabled? | You can just check the value of the constant.
if( WP_DEBUG === true ) {
// enabled
} else {
// not enabled
} | stackexchange-wordpress | {
"answer_score": 14,
"question_score": 7,
"tags": "php, theme development"
} |
Post added by PHP redirects to 404
On my blog on < you can see the few posts I added.
They are aaded via PHP. The stragen thing is when I click on the post it
does not open the post. The same happens if I added the post over dashboard.
Why? | Look at how to use Using_Permalinks in WordPress.
Set your **Common Settings** to **Post Name** and save. When you click save it should flush_rewrite_rules but you may need to do that manually.
, making a post type hierarchical would be fatal. Because Wordpress builds trees for hierarchical post types in the back end, which is really expensive operations, you will get a fatal error due to memory exhausted or maximum time exceeded if you have hundreds or thousands of posts.
## EDIT
With the amount of posts that you are planning, you should be fine, although you will find that your back end page for that post type will load much slower. If you can live with that, well, yes, then you are good to go | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "custom post types, hierarchical"
} |
Get current day using javascript
I'm trying to get the current date using JavaScript. Is it possible to do that?
I want to add classes to some DOM element and it depends of the day of the week. Which element should I add to this class? | I've an approach for you, getting the WordPress date in JavaScript, a numb one, but still an approach: :)
### functions.php
wp_enqueue_script( 'wpse-custom-scripts', get_template_directory_uri() .'/js/wpse-custom.js', array('jquery'), '1.0.0', true );
wp_localize_script(
'wpse-custom-scripts',
'wpse',
array(
'date_time_now' => date( 'Y-m-d H:i:s', current_time( 'timestamp' ) ), //format: YYYY-MM-DD 00:00:00
)
);
### wpse-custom.js
jQuery(document).ready(function($) {
console.log("WordPress date now: " + wpse.date_time_now);
});
It's not a better approach, I know. | stackexchange-wordpress | {
"answer_score": 0,
"question_score": -2,
"tags": "javascript"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.