#StackBounty: #functions #read-more Why does modifying the "read more" link remove the link class?

Bounty: 50

I’m using the following code (found on the WordPress.org site) to modify my (more…) text:

//Modify "read more" text
function modify_read_more_link() {
    return '<a class="more-link" href="' . get_permalink() . '">(Continue…)</a>';
}
add_filter( 'the_content_more_link', 'modify_read_more_link' );

The code works as expected, in the sense that (more…) is properly replaced by (Continue…), and the link works as intended. However, there is a peculiar issue: The class more-link has disappeared, which means styling doesn’t work. I attempted to circumnavigate the issue by adding styling inline (return '<a style="font-size:0.8em;" href="' . get_permalink() . '">(Continue…)</a>';) but that hasn’t worked either.

My Question:
Why has the class more-link disappeared, and how can I restore it?

Note: I add the code above to functions.php; I’m not using a child theme.


Get this bounty!!!

#StackBounty: #bash #functions A function can only be called if its name is the first word of an expression?

Bounty: 50

A function can only be called if its name is the first word of an expression, as is the case with aliases?
Or can it also be the nth word of an expression?
I can’t emulate a use case that answers this question of mine.
I can’t find a guide that answers this question of mine.
Being Italian, I find it difficult to find the right words on the Google search engine.
Can you also mention the source in the answer?
Thank you.


Get this bounty!!!

#StackBounty: #php #posts #wp-query #functions posts_per_page displays only 2 posts instead of 4 posts

Bounty: 50

I have a wordpress/php code as shown below in which I am trying to pull latest 4 channels at Line A in the code below.

function get_latest_channels( $instance_id = false ) {
    echo $instance_id;
    echo "<br>";
    if ( ! $instance_id ) {
        $query_args = array(
                'post_type'      => 'hello-channels',
                'ep_integrate'   => true,
                'posts_per_page' => 4,
        );
    } else {
        $query_args = array(
                'post_type'      => 'hello-channels',
                'ep_integrate'   => true,
                'meta_key'       => 'instance_id',
                'meta_value'     => $instance_id,
                'posts_per_page' => 4,
        );
    }
    $channels = new WP_Query( $query_args );
    if ( $channels->have_posts() ) {
        $rtn = $channels->posts;
    }

    return $rtn;
}

$instance_id = 49;
$latest_channels = HELLOChannelsget_latest_channels($instance_id);
echo "<pre>"; print_r($latest_channels); echo "</pre>". // Line A

The value of $instance_id is 49. On using 49 value, it should pull 4 latest channels.

Problem Statement:

My code is working fine dev/staging server (meaning its pulling latest 4 channels at Line A) but in production server its pulling only 2 channels.

I am wondering what changes I need to make in the php code above so that it pulls latest 4 channels in the production server.

If I comment this line 'posts_per_page' => 4, in the else section of the function get_latest_channels( $instance_id = false ) then Line A is pulling 30 posts in dev server.


Get this bounty!!!

#StackBounty: #php #posts #functions posts_per_page displays only 2 posts instead of 4 posts

Bounty: 50

I have a wordpress/php code as shown below in which I am trying to pull latest 4 channels at Line A in the code below.

function get_latest_channels( $instance_id = false ) {
    echo $instance_id;
    echo "<br>";
    if ( ! $instance_id ) {
        $query_args = array(
                'post_type'      => 'hello-channels',
                'ep_integrate'   => true,
                'posts_per_page' => 4,
        );
    } else {
        $query_args = array(
                'post_type'      => 'hello-channels',
                'ep_integrate'   => true,
                'meta_key'       => 'instance_id',
                'meta_value'     => $instance_id,
                'posts_per_page' => 4,
        );
    }
    $channels = new WP_Query( $query_args );
    if ( $channels->have_posts() ) {
        $rtn = $channels->posts;
    }

    return $rtn;
}

$instance_id = 49;
$latest_channels = HELLOChannelsget_latest_channels($instance_id);
echo "<pre>"; print_r($latest_channels); echo "</pre>". // Line A

The value of $instance_id is 49. On using 49 value, it should pull 4 latest channels.

Problem Statement:

My code is working fine dev/staging server (meaning its pulling latest 4 channels at Line A) but in production server its pulling only 2 channels.

I am wondering what changes I need to make in the php code above so that it pulls latest 4 channels in the production server.

If I comment this line 'posts_per_page' => 4, in the else section of the function get_latest_channels( $instance_id = false ) then Line A is pulling 30 posts in dev server.


Get this bounty!!!

#StackBounty: #functions #users #forms #permissions Add new user : make the fields First Name and Last name required

Bounty: 50

I’m searching how to make First Name and Last name fields required when we add a new user. Right now only username and Email fields are required.

I found a way by adding class="form-required" for the first and last name fields on the file user-new.php.

But I’m looking for a method with adding code on function.php and not touch to the WordPress Core.

Thanks.


Get this bounty!!!

#StackBounty: #posts #functions #rest-api #security #json Disable REST API for a user ROLE

Bounty: 50

I’m looking for a way to disable Rest API for a user role called ‘external_user’ (disable wp-json queries.)

This user role can see right now alot of posts and pages information with when we put wp-json on the URL (users, pages, posts…)

I use actually the plugin DISABLE REST API but it prevent only not logged users to see json informations. i need to do the same thing with external_user role.

If it’s not possible, can I redirect this user role (and only external_user role) to 404 pages if he try to put an URL with wp-json ?

Thanks.


Get this bounty!!!

#StackBounty: #plugins #php #plugin-development #functions #publish HELP: Integrating WP with raw PHP code once published button is hit

Bounty: 50

Hello guys let me just open up, I am not good in both Wp coding, I will like to integrate my wp site so that once the published/update button is hit, it will automatically import external mp3 file to my server and as well change the external mp3 link to the that is just imported to my server, however this has been done, here is the code I used though its a plugin.

class DX_Auto_Save_Images{

    function __construct(){     

        //filter and action hook
        add_filter( 'content_save_pre',array($this,'post_save_images') );   //save images
        add_action( 'admin_menu', array( $this, 'menu_page' ) );        //menu page
        add_filter( 'intermediate_image_sizes_advanced', array( $this, 'remove_tmb' ) );    //remove tmb
        add_action( 'submitpost_box', array( $this, 'submit_box' ) );   //submit_box
        add_action( 'submitpage_box', array( $this, 'submit_box' ) );   //submit_box
    }



    //save post exterior images
    function post_save_images( $content ){
        if( ($_POST['save'] || $_POST['publish']) && ($_POST['DS_switch']!='not_save') ){
            set_time_limit(240);
            global $post;
            $post_id=$post->ID;
            $preg=preg_match_all('/<a.*?href="(.*?)"/',stripslashes($content),$matches);
            if($preg){
                $i = 1;
                foreach($matches[1] as $image_url){
                    if(empty($image_url)) continue;
                    $pos=strpos($image_url,get_bloginfo('url'));
                    if($pos===false){
                        $res=$this->save_images($image_url,$post_id,$i);
                        $replace=$res['url'];
                        $content=str_replace($image_url,$replace,$content);
                    }
                    $i++;
                }
            }
        }
        remove_filter( 'content_save_pre', array( $this, 'post_save_images' ) );
        return $content;
    }



    //save exterior images
    function save_images($image_url,$post_id,$i){
        $file=file_get_contents($image_url);

                $_filter = true; // For the anonymous filter callback below.
add_filter( 'upload_dir', function( $arr ) use( &$_filter ){
    if ( $_filter ) {


         $arr['path'] = $arr['basedir'] . '/music' .$arr['subdir'];
        $arr['url'] = $arr['baseurl'] . '/music' .$arr['subdir'];



      //  $folder = '/org_logos'; // No trailing slash at the end.
      //  $arr['path'] .= $folder;
      // $arr['url'] .= $folder;
      // $arr['subdir'] .= $folder;




        /*THE BELOW IS FOR IS TO UPLOAD IT TO MUSIC CATEGORY WITHOUT YEAR AND MONTH BY ENTERMASTER. THIS SCRIPT IS WORKING FINE
        $arr['path'] = $arr['basedir'] . '/music';
        $arr['url'] = $arr['baseurl'] . '/music';
        $arr['subdir'] = '/music';
        */
    }

    return $arr;
} );

        $filename=basename($image_url);
        $options = get_option( 'dx-auto-save-images-options' );



        if( $options['chinese']=='yes' ){
          preg_match( '/(.*?)(.w+)$/', $filename, $match );
          $im_name = md5($match[1]).$match[2];      
        }
        else $im_name = $filename;
        $res=wp_upload_bits($im_name,'',$file);
    //  $res=wp_upload_bits($im_name,'',$file);
    //  $attach_id = $this->insert_attachment($res['file'],$post_id);
    //  if( $options['post-tmb']=='yes' && $i==1 ){
        //  set_post_thumbnail( $post_id, $attach_id );
    //  }
        return $res;
        $_filter = false; // Disables the filter.
    }

    //insert attachment
    function insert_attachment($file,$id){
    //  $dirs=wp_upload_dir();
        $filetype=wp_check_filetype($file);
/*      $attachment=array(
        //  'guid'=>$dirs['baseurl'].'/music/'._wp_relative_upload_path($file),
            'post_mime_type'=>$filetype['type'],
            'post_title'=>preg_replace('/.[^.]+$/','',basename($file)),
            'post_content'=>'',
            'post_status'=>'inherit'
        ); */
    //  $attach_id=wp_insert_attachment($attachment,$file,$id);
    //  $attach_data=wp_generate_attachment_metadata($attach_id,$file);
    //  wp_update_attachment_metadata($attach_id,$attach_data);
    //  return $attach_id;
    }

    //menu page
    function menu_page(){
        add_menu_page( 'DX-auto-save-mp3','Auto Import Mp3 File locally', 'manage_options', 'DX-auto-save-mp3', array( $this, 'options_form' ), plugins_url( 'icon.png', __FILE__ ) );
    }

    //options form
    function options_form(){
        $options = $this->save_options();
        include( 'options-form.php' );
    }

    //form bottom action
    function form_bottom(){
?>
    <div id="form-bottom" style="width:650px;border:1px dotted #ddd;background-color:#f7f7f7;padding:10px;margin-top:20px;">
        <p>For more coding by entermaster visit: <a href="https://www.gidiportal.com/" target="_blank">https://www.gidiportal.com</a></p>

    </div>  
<?php
    }

    //save options
    function save_options(){
        if( $_POST['submit'] ){
            $data=array(
                'tmb' => $_POST['tmb'],
                'chinese' => $_POST['chinese'],
                'switch' => $_POST['switch'],
                'post-tmb' => $_POST['post-tmb']
            );
            update_option( 'dx-auto-save-images-options', $data );
        }
        return get_option( 'dx-auto-save-images-options' );
    }

    //remove tmb
    function remove_tmb( $sizes ){
        $options = get_option( 'dx-auto-save-images-options' );
        if( $options['tmb']=='yes' ){
            $sizes = array();
        }
        return $sizes;
    }

    //get_sample_permalink_html
    function submit_box(  ){
        $options = get_option( 'dx-auto-save-images-options' );
        if( $options['switch'] == 'yes' ){
            echo '<span style="padding-bottom:5px;display:inline-block;"><input type="checkbox" name="DS_switch" value="not_save"/> 不保存远程图片.</span>';
        }
    }

}

//new
new DX_Auto_Save_Images();

Though I modified a plugin to get this result working.

Now i want to integrate this code to work with ID3 php music script i already have, so that i can be able to change both the album art, the title of the song and artiste name will just match exactly the one on the wp post title, then the imported external url in the wp content will pass through this php script once the publish button is hit it will just work on the back end and change the link on wordpress editor. here is the below php script, how ever the php part of the script it is working fine if i run it on browser, this is just the index of the script i want to integrate with wp to work together.

<?php
error_reporting(0);
require ( 'getid3/getid3.php' ) ;

require ( 'getid3/join.php' ) ;


if( isset($_POST['submit'])){
$now = time() ;
$default_mp3_directory =  "../wp-content/uploads/music/";
$default_album = "Example.com";
$default_year = date("Y", $now);
$default_genre = "Example.com";
$default_producer = '';
$default_cover = './music.jpg';
$shownUrl = 'https://www.Example.com/wp-content/uploads/music/';
# To the real uploads

$mp3_filepath = trim($_POST['url']);
$mp3_songname = trim($_POST['title']);
$mp3_comment = "Downloaded from Example.com";;
$mp3_artist = trim($_POST['artiste']);
$artiste = $mp3_artist;
$pFilename = trim($_POST['filename']);
$mp3_filename = empty( $pFilename ) ? $mp3_artist.' - '.$mp3_songname : $pFilename;
$mp3_album = empty ( $_POST['album'] )  ? $default_album : trim ( $_POST['album'] );
$mp3_year = empty ( $_POST['year'] ) || !is_numeric($_POST['year']) || strlen($_POST['year']) != 4 ? $default_year : $_POST['year'];
$mp3_genre = empty ( $_POST['genre'] ) ? $default_genre : $_POST['genre'];
$extra = array ( 'year' => $mp3_year, 'genre' => trim($_POST['genre']), 'album' => trim($_POST['album']), 'producer' => ! empty ( $_POST['producer']) ? trim($_POST['producer']) : $default_producer );
$error = '';

# Checking the mp3

if( !filter_var($mp3_filepath, FILTER_VALIDATE_URL)){
$error .= 'Invalid File URL<br>';
} else if ( empty($mp3_filename) OR empty ($mp3_songname) OR empty($mp3_artist)){
$error .= "Fields Marked * Are Required<br>";
} else if ( !file_exists($default_cover) ) {
$error .= 'The Photo Cover Has Not Been Uploaded';
} else {
$timeFolder .= date('Y', $now) . '/' . date('m', $now) . '/';
if(!file_exists($default_mp3_directory . $timeFolder)){ mkdir($default_mp3_directory . $timeFolder, 0777, true); }
$invalidchars = array("'", '"', '.', ',');
$storeName = str_replace($invalidchars, '', $mp3_filename); // . '_[Example.com].mp3';
$storeName = preg_replace('/[^A-Z-a-z0-9-_]/', '_', $storeName);
$storeName = preg_replace("/_{2,}/", "_", $storeName);
$storeName .= '_Example.com_.mp3';
$sname = $default_mp3_directory . $timeFolder . $storeName;
if (file_exists($sname) ) {
$error = 'File Has Alread Been Uploaded As <a href="' . $shownUrl . $timeFolder . $storeName . '">' . $storeName . '</a>';
} else {
if(copy($mp3_filepath, $sname)){
# Rewrite tags
$mp3_tagformat = 'UTF-8';
$mp3_handler = new getID3;
$mp3_handler->setOption(array('encoding'=>$mp3_tagformat));



//Add audio file

$tmp_name= "tmp/$storeName";

copy($sname,$tmp_name);

//$file_go_in[] = "voice.mp3";
$file_go_in[] = $tmp_name;
$file_go_in[] = "voice.mp3";
$file_go_out = $sname;

merge_mp3($file_go_out,$file_go_in);

unlink($tmp_name);





# The writer class
require ( 'getid3/write.php' ) ;

$mp3_writter = new getid3_writetags;


$mp3_writter->filename       = $sname;
$mp3_writter->tagformats     = array('id3v1', 'id3v2.3');
$mp3_writter->overwrite_tags = true;
$mp3_writter->tag_encoding   = $mp3_tagformat;
$mp3_writter->remove_other_tags = true;

$mp3_data['title'][]   = $mp3_songname.' | Example.com';
$mp3_data['artist'][]  = $mp3_artist;
$mp3_data['album'][]   = $mp3_album;
$mp3_data['year'][]    = $mp3_year;
$mp3_data['genre'][]   = $mp3_genre;
$mp3_data['comment'][] = $mp3_comment;
$mp3_data['attached_picture'][0]['data'] = file_get_contents($default_cover);
$mp3_data['attached_picture'][0]['picturetypeid'] = "image/jpeg";
$mp3_data['attached_picture'][0]['description'] = "Downloaded from Example.com";
$mp3_data['attached_picture'][0]['mime'] = "image/jpeg";
$mp3_writter->tag_data = $mp3_data;

if ( $mp3_writter->WriteTags() ) {
$link = $sname ;
$shownUrl .= $timeFolder . $storeName;
} else {
unlink ( $sname );
$error .= "Failed To Write Tags!<br><br><em>" . implode( "<br><br>", $mp3_writter->errors ) . '</em><br>';
}
} else {
$error .= "Unable To Copy File";
}
}
}
}
?> <!DOCTYPE html> <html> 
<meta name="viewport" content="width=device-width, initial-scale=1" />
</html>


<?php if ( isset ( $link ) && ! empty ( $link ) ) { ?>
<div class="successbox">
File Uploaded Successfully
<p class="copy"><input type="text" value="<?php echo $shownUrl; ?>"></p>
</div>

<?php } else {  ?>
<?php if ( ! empty ( $error ) ) { ?>
<div class="error"><?php echo $error; ?></div>
<?php } ?>
<form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<div>
<div class="dark1"><b><font size="2">Link</font><br></b>
<input type="text" name="url" value="<?php echo $_POST['url']; ?>">
</div></div>

<div>
<div class="dark1"><b><font size="2">Title</font><br></b>
<input type="text" name="title" value="<?php echo $_POST['title']; ?>">
</div>
</div>

<div>
<div class="dark1"><b><font size="2">Artiste</font><br></b>
<input type="text" name="artiste" value="<?php echo $_POST['artiste']; ?>">
</div>

<div>
<div class="dark1"><b>Album<br></b>
<input type="text" name="album" value="Example.com">
</div>
<div>
<div class="dark1"><b>Producer<br></b>
<input type="text" name="producer" value="Example.com">
</div></div>
<div>

<div class="">
<input type="submit" name="submit" value="Upload">
</div>
</form></div>
<?php } ?>
<br />

</body>
</html>


Get this bounty!!!

#StackBounty: #sql-server #optimization #stored-procedures #sql-server-2017 #functions SQL Server 2017 Stored Proc & TVF Performanc…

Bounty: 50

I have a SQL Server 2017 Enterprise Edition instance where a stored procedure was taking approx. five minutes to execute. After reviewing the stored procedure code, I could see that there was an inline scalar UDF referenced several times in the SELECT list and also in the predicate WHERE clause of the stored procedure body.

I advised the application team owning the code that they should refactor their stored proc not to use an inline UDF which they took onboard and replaced with a TVF. Whilst they were doing this, I noticed that the application database still had database compatibility level 100 so I raised this to the latest level of 140 after running the database through the Data Migration Assistant to check for deprecated features and breaking changes.

Following the replacement of the UDF for a TVF and raising the database compatibility level from 100 to 140, the performance has increased greatly and the stored proc now executes in under a minute but performance is still not where I’d like to it be. I’m hoping someone might be able to advise of anything obvious I’m missing or point me in the right direction of anything else I can do to further optimise the code or get this to perform better? The execution plan is here: https://www.brentozar.com/pastetheplan/?id=ByrsEdRpr

The code for the stored proc and function are as below and the stored procedure is called by the application as such: “EXEC dbo.CAOT_GetApplicationQueue;1”

/****** Object: StoredProcedure [dbo].[CAOT_GetApplicationQueue] ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[CAOT_GetApplicationQueue]
(@userID VARCHAR(50)='', @showComplete CHAR(1)='N', @JustMyQueue BIT=0, @ChannelId VARCHAR(10) = NULL )
AS
BEGIN
SELECT App.pkApplication ,
COALESCE(ApplicationReference, AlternateApplicationReference) AS ApplicationReference ,
ApplicationDate ,
Name ,
Telephone ,
[Address] ,
Email ,
CIN ,
Dob ,
CreatedDate ,
BusinessPhone ,
PostCode ,
MobilePhone ,
[Action] ,
ActionStatus ,
branchNumber ,
AccountNumber ,
AccountType ,
act.accountDescription,
IsNull( appstatus.DESCRIPTION ,'-- CREATED --') As LastStatus,
IsNull(appstatus.DAYS,'0') DaysSinceLastStatus ,
DATEDIFF(d,ApplicationDate, GETDATE()) DaysCreated,
InitialUserID,
IsNull(appstatus.STATUS,'-- MADE --') APPLICATIONSTATUS
FROM dbo.CAOT_Application (NOLOCK) app
LEFT OUTER JOIN dbo.CAOT_AccountType (NOLOCK) act
ON app.AccountType = act.AccountTypecode
LEFT OUTER JOIN [CAOT_GetAllApplicationStatus]() appstatus
ON app.pkApplication = appstatus.[PKAPPLICATION]
WHERE (IsNull(appstatus.STATUSCODE,'MADE') NOT IN ('CANCELLED','DECLINED','COMPLETE','EXPIRED')
OR @showComplete='Y') AND
(@JustMyQueue = 0 OR InitialUserID = @userID) AND
(@ChannelId IS NULL OR ChannelID = @ChannelId OR (@ChannelId = 'CBU' AND ChannelID IS NULL AND isCAO='N'))
ORDER BY CASE WHEN InitialUserID = @userid THEN 10 ELSE 900 END, ApplicationDate DESC
END
GO

/****** Object: UserDefinedFunction [dbo].[CAOT_GetAllApplicationStatus] ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[CAOT_GetAllApplicationStatus]() RETURNS
@return TABLE
(
[PKAPPLICATION] [int] NOT NULL,
[PKAPPLICATIONEVENT] INT,
[EVENTCREATEDDATE] [DATETIME] NULL,
[KEY] VARCHAR(12) NULL,
[DESCRIPTION] VARCHAR(200) NULL,
[CODE] VARCHAR(20) NULL,
[DAYS] VARCHAR(20) NULL,
[STATUS] VARCHAR(200) NULL,
[STATUSCODE] VARCHAR(50) NULL
)

AS
BEGIN

Declare @AppStatus table
(
[PKAPPLICATION] [int] NOT NULL,
[PKAPPLICATIONEVENT] INT,
[EVENTCREATEDDATE] [DATETIME] NULL,
[KEY] VARCHAR(12) NULL,
[DESCRIPTION] VARCHAR(200) NULL,
[CODE] VARCHAR(20) NULL,
[DAYS] VARCHAR(20) NULL,
[STATUS] VARCHAR(200) NULL,
[STATUSCODE] VARCHAR(50) NULL
)

INSERT INTO @AppStatus

SELECT
fkApplication,
ev.pkApplicationEvent As pkApplicationEvent,
ev.CreateDate As 'EventCreatedDate',
CONVERT(VARCHAR(12), evt.fkApplicationStatus) As 'KEY',
evt.EventDescription As 'DESCRIPTION',
evt.EventCode As 'CODE' ,
CONVERT(VARCHAR(20), DATEDIFF(d, ev.createdate, GETDATE()) ) As 'DAYS',
apps.StatusDescription As 'STATUS' ,
apps.StatusCode As 'STATUSCODE'
FROM dbo.CAOT_ApplicationEvent (NOLOCK) ev
INNER JOIN dbo.CAOT_EventType (NOLOCK) evt ON ev.fkEventType = evt.pkEventType
INNER JOIN dbo.CAOT_ApplicationStatus (NOLOCK) apps ON evt.fkApplicationStatus = apps.pkApplicationStatus

ORDER BY ev.CreateDate DESC, ev.pkApplicationEvent DESC

INSERT INTO @return
Select * from @AppStatus AllStatus
Where AllStatus.EVENTCREATEDDATE = ( Select Max(LatestAppStatus.EVENTCREATEDDATE) from @AppStatus LatestAppStatus where LatestAppStatus.PKAPPLICATION =AllStatus.PKAPPLICATION ) --Z On X.PKAPPLICATION = Z.PKAPPLICATION

RETURN
END

GO


Get this bounty!!!